28 Ekim 2014 Salı

C# chrome ve firefox versiyon çekme

Chrome ve firefox ile versiyon çekme

using System;
using System.Diagnostics;
using Microsoft.Win32;

class Program
{
    static void Main(string[] args)
    {
        object path;
        path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
        if (path != null)
            Console.WriteLine("Chrome: " + FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion);

        path = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\firefox.exe", "", null);
        if (path != null)
            Console.WriteLine("Firefox: " + FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion);
    }
}

Selenium linke tıklatma

Selenium linke tıklatma işlemi nasıl yapılır örnek kodlar.
driver.FindElement(By.ClassName("ms-vb")).Click();
 wait.Until(x => x.FindElement(By.LinkText("Target link to click"))); driver.FindElement(By.LinkText("Target link to click")).Click();

C# ekrandaki aktif programları alma

c# ile ekrandaki aktif programları almak
var openWindowProcesses = System.Diagnostics.Process.GetProcesses().Where(p => p.MainWindowHandle != IntPtr.Zero);
Use that with a timer right before you start the process to wait for the 3rd party app window to show up.
UPDATE
foreach (var item in openWindowProcesses)
{
    Console.WriteLine(GetWindowTitle(item.MainWindowHandle));
}

[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, uint fuFlags, uint uTimeout, out IntPtr lpdwResult);

private static string GetWindowTitle(IntPtr windowHandle)
{
    uint SMTO_ABORTIFHUNG = 0x0002;
    uint WM_GETTEXT = 0xD;
    int MAX_STRING_SIZE = 32768;
    IntPtr result;
    string title = string.Empty;
    IntPtr memoryHandle = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(MAX_STRING_SIZE);
    System.Runtime.InteropServices.Marshal.Copy(title.ToCharArray(), 0, memoryHandle, title.Length);
    SendMessageTimeout(windowHandle, WM_GETTEXT, (IntPtr)MAX_STRING_SIZE, memoryHandle, SMTO_ABORTIFHUNG, (uint)1000, out result);
    title = System.Runtime.InteropServices.Marshal.PtrToStringAuto(memoryHandle);
    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(memoryHandle);
    return title;
}

C# program kapanana kadar bekleme

c# ile bir uygulamayı çalıştırdıktan sonra kapanmasını bekleme

System.Diagnostics.Process process = System.Diagnostics.Process.Start("cmd.exe");
        while (!process.HasExited)
        {
            //update UI
        }

alternatif

var process = Process.Start("popup.exe");
while(process.MainWindowTitle != "Title")
{
    Thread.Sleep(10);
}

27 Ekim 2014 Pazartesi

C# txt belli karakterden sonrasını silme

C# ile metin belgesi içindeki listeden belli karakterden sonrasını silmek için lazım olan kodlar aynı zamanda tekrar eden ifadeleride siler.

  var sr = new StreamReader(File.OpenRead(@"deneme.txt"));
            var sw = new StreamWriter(File.OpenWrite(@"son.txt"));
            var lines = new HashSet<int>();
            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();

                int bb=line.IndexOf("?");
                if (bb > 4)
                {
                    line = line.Substring(0, bb);
                }
                int hc = line.GetHashCode();
                if (lines.Contains(hc))
                    continue;

                lines.Add(hc);
                sw.WriteLine(line);
            }
            sw.Flush();
            sw.Close();
            sr.Close();

24 Ekim 2014 Cuma

C# aynı elemanları txt den silme

Aynı olan elemanları silme,txt aynı olanları silme c# ile nasıl yapıldığını gösterdik.Not defteri dosyasındaki aynı elemanları temizlemek için kodumuz net 3.5 gerektirir.Tekrar eden dublicated elemanlardan bu sayede kurtulabilirsiniz.Bir de şu nokta var eğer domain temizletmek istiyorsanız ve unique bir list elde etmek istiyorsanız .Önce domaini almalı daha sonra bunu içeren diğer elemanları silmelisiniz....


private void button1_Click(object sender, EventArgs e)
        {
            var readLines = File.ReadAllLines("deneme.txt", Encoding.Default);

            File.WriteAllLines("bitti.txt", readLines.Distinct().ToArray(), Encoding.Default);
        }

12 Ekim 2014 Pazar

C# GOOGLE ALERTS

C# google alerts çekme

public static string HttpGet()
            {
            WebClient client = new WebClient();

            // Add a user agent header in case the  
            // requested URI contains a query.

            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            using (Stream data = client.OpenRead("http://www.google.com/alerts/feeds/11811034629636691510/10685173545303329123"))
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string s = reader.ReadToEnd();

                }
            }
        }

3 Ekim 2014 Cuma

c# crawler

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 Tool;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace Search
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /**
        * Queue, save will access the URL
        */
        public class Queue
        {
            //Use list queue
            private LinkedList<string> queue = new LinkedList<string>();
            //The queue
            public void enQueue(string t)
            {
                queue.AddLast(t);
            }
            //The queue
            public string deQueue()
            {
                string o = queue.Last.Value;
                 queue.RemoveLast();
                 return o;

            }
            //To judge whether the queue is empty
            public bool isQueueEmpty()
            {
                return queue.Count > 0 ? false : true;
            }
            //Judge whether the queue contains T
            public bool contians(string t)
            {
                return queue.Contains(t);
            }
            public int getcount()
            {
                return queue.Count;
            }
        }
        public class LinkQueue
        {
            //Have access to the URL collection
            private static ISet<string> visitedUrl = new HashSet<string>();
            //To visit the URL collection
            private static Queue unVisitedUrl = new Queue();
            //URL queue
            public static Queue getUnVisitedUrl()
            {
                return unVisitedUrl;
            }
            //Add to queue URL visited in
            public static void addVisitedUrl(String url)
            {
                visitedUrl.Add(url);
            }
            //Remove access over URL
            public static void removeVisitedUrl(String url)
            {
                visitedUrl.Remove(url);
            }
            //No access to the URL queue
            public static Object unVisitedUrlDeQueue()
            {
                return unVisitedUrl.deQueue();
            }
            // To ensure that each URL is visited only once
            public static void addUnvisitedUrl(String url)
            {
                if (url != null && !url.Trim().Equals("")
                && !visitedUrl.Contains(url)
                && !unVisitedUrl.contians(url))
                    unVisitedUrl.enQueue(url);
            }
            //Get the number URL has access to
            public static int getVisitedUrlNum()
            {
                return visitedUrl.Count;
            }
            //Whether the empty queue URL judgment not visit in the
            public static bool unVisitedUrlsEmpty()
            {
                return unVisitedUrl.isQueueEmpty();
            }
        }


        string[] urlarr=new string[100];
        private void button1_Click(object sender, EventArgs e)
        {
            zzHttp http = new zzHttp();
            CookieContainer cookie = new CookieContainer();
            string url = textBox1.Text!=""?textBox1.Text:"http://image.baidu.com/";
            string content=http.SendDataByGET(url,"",ref cookie);

            string baseUri = Utility.GetBaseUri(url);
            string[] links = Parser.ExtractLinks(baseUri, content);
            foreach (string link in links)
            {
                richTextBox1.Text += link;
                richTextBox1.Text += "\n";
            }


            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);            // Search string            
            MatchCollection matches = regImg.Matches(content);            

            Queue que = new Queue();
            foreach (Match match in matches)
                que.enQueue(match.Groups["imgUrl"].Value);
            int k;
            for (k = 0; k <que.getcount(); k++)
            {
                string picurl = que.deQueue();
                richTextBox1.Text += picurl;
                richTextBox1.Text += "\n";

                string[] s = picurl.Split('/');
                string picname=s[s.Length - 1];
                zzHttp.downfile(picurl, picname, @"d:\pic\");
            }
            label1.Text = k+"Zhang";
        }

        //Search
        void search()
        {
            int i = 0;
            LinkQueue.addUnvisitedUrl(" ;);
            while (!LinkQueue.unVisitedUrlsEmpty()
            && LinkQueue.getVisitedUrlNum() <= 1000)
            {
                
                //Team a queue head URL
                String visitUrl=(String)LinkQueue.unVisitedUrlDeQueue();
                if(visitUrl==null)
                    continue;
                zzHttp downLoader = new zzHttp();
                CookieContainer cookie = new CookieContainer();
                 //Download Webpage
                string content=downLoader.SendDataByGET(visitUrl,"",ref cookie);
                //The URL in access in URL
                LinkQueue.addVisitedUrl(visitUrl);
                //Extract the downloaded Webpage in URL
                string baseUri = Utility.GetBaseUri(visitUrl);
                string[] links = Parser.ExtractLinks(baseUri, content);
                //New unvisited URL enqueue
                i++;
                Add2Message("Has access number:" + LinkQueue.getVisitedUrlNum() + ",count=" + LinkQueue.getUnVisitedUrl().getcount());
                foreach (string link in links)
                {
                    if (link.Contains("css") || link.Contains("js") || link.Contains("gif") || link.Contains("jpg") || link.Contains("png") || link.Contains("jpeg"))
                        continue;
                    LinkQueue.addUnvisitedUrl(link);
                    AddMessage(link);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
          new Thread(search).Start();
        }

        private delegate void InfoDelegate(string message);
        public void AddMessage(string message)
        {
            if (richTextBox1.InvokeRequired)//Cannot access it creates a delegate
            {
                InfoDelegate d = new InfoDelegate(AddMessage);
                richTextBox1.Invoke(d, new object[] { message});
            }
            else
            {
                richTextBox1.AppendText(message + Environment.NewLine);
                richTextBox1.ScrollToCaret();
            }
        }
        private delegate void Info2Delegate(string message);
        public void Add2Message(string message)
        {

            if (label2.InvokeRequired)//Cannot access it creates a delegate
            {
                Info2Delegate d = new Info2Delegate(Add2Message);
                label2.Invoke(d, new object[] { message });
            }
            else
            {
                label2.Text = message;
            }
        }
    }
}