21 Ağustos 2016 Pazar

C# Visual Studio DLL import hatasının Çözümü

Visual Studio da böyle bir hatayla karşılaştıysanız çözümü çok basit yapmanız gereken tek şey ” using System.Runtime.InteropServices; ” eklemek.. Sorun çözülecektir.

C# da dll Oluşturma ve Kullanma

Dynamic Linking Library olarak adlandırılan ve en kısa tanımı ile uygulamalarımızın kullandığı kütüphane dosyalarının barındırıldığı dosya yapısıdır.

Bize Faydası Nedir?
Esasında biz dll leri istesek de, istemesek de C# kullanıyoruz. Fakat bunlar hazır yazılmış dll ler oluyor. Peki kendi dll mizi yazmanın bize ne gibi faydası olacak? Sorunun cevabı çok basit cok kod yazmaktan kurtulmak ve projenin gereğinden fazla şişmesini engellemek.

Basit bir örnek vermek gerekse “MessageBox.Show” bunu cok sık kullanmışızdır. Yazdığımızda mesaj kutusu çıkar. Fakat biz böyle bir şey eklemeyiz projemize, çünkü Sytem.Windows.Forms namespace i içinde yer almaktadır. Bu namespace ler bir dll dosyası içinde tanımlanmıştır.

Bir Dll Oluşturalım
VisualStduio nun açılış ekranın da Create Project e tıkladıktan sonra genelde Console Application veya Windows Application a tıklamışızdır. Fakat bu sefer Class Library e tıklıyoruz.

Şimdi örnek olarak bir MD5 oluşturucu Dll yazalım.
Önce Project->Add Reference->.NET->System.Web i referans olarak ekliyoruz. Bu eklediğimiz referans sayesince string bir değişkeni md5 haline getirebiliriz.

İkinci adım olarak aşağıdaki kodları ekleyin:
namespace MD5Olustur
{
    public class Hash
    {
        private string hash;
        public string Cevir(string pass)
        {
            this.hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pass, "md5");
            return hash;
        }
    }
}

bunları yazıp çalıştırdığınızda uyarı gibi bir şey alacaksınız. Bu projenizin derlendiği anlamına gelmektedir. \\\\bin\\\\Debug içinde .dll niz oluşmuş olacak.

burada;
Hash Sınıfımızın adı
Cevir Metodumuzun adı dır.
Bir Dll yi Kullanma

Yeni bir proje açıyoruz (Windows Application …) bu sefer projemize az önce oluşturduğumuz dll dosyamızı referans olarak ekliyoruz.
Project->Add Reference->Browse->[oluşturduğumuz Dll nin klasörüne gidiyoruz] Dll mizi seçiyoruz.
NameSpace olarak ise using Dllmizin_adi;
Örnek: using MD5Olustur;
Dll mizin içindeki class ları kullanmak için:
Classımızın_Adı nesnemizin adı=new Classımızın adı();
Örnek : Hash md5 = new Hash();

String bir değeri dll miz sayesinde md5 yapmak için:
yenihash = md5.Cevir(textBox2.Text);
eskihash = md5.Cevir(textBox1.Text);

Peki Dll miz Olmasaydı Bunu Nasıl Yapardık
Önce Projemize Dll mize eklediğimiz gibi System.Web Referansını eklerdik.
Sonra:
pass=Convert.ToString(textBox1.Text);
eskihash=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pass, "md5");
…
Peki başka bir Proje de yine MD5 cevirmeye gerek duyulursa… o zaman yine System.Web referansını ekleyip her çevirme için yukardaki satırı yazacağız yada oluşturduğumuz dll yi kullanıp kendi oluşturduğumuz şekilde yapacağız.

MD5Olustur.dll mizin linki:

bu resimde de kendi dll mizle olusturdugumuz bir program ile klasik yontem arasındaki farkı görebilirsiniz

14 Ağustos 2016 Pazar

c# get div text from webbrowser

HtmlDocument doc = webBrowser1.Document;
        HtmlElementCollection divs = doc.GetElementsByTagName("div");

        foreach (HtmlElement div in divs)
        {
            try
            {
                var info = div.DomElement;
                PropertyInfo[] pi = info.GetType().GetProperties();

                string strClass = pi[0].GetValue(div.DomElement).ToString();

                if (strClass == "cls")
                {
                        //DoStuff
                }
            }
            catch
            {

            }

12 Ağustos 2016 Cuma

c# xpath contains

//div[contains(@id,'test')]
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Html Agility Pack

Here are some examples with the general concepts.
Open HTML document from a URL:
HtmlWeb web = new HtmlWeb();
HtmlDocument html = web.Load(url);
Get all rows in the entire document:
var rows = html.DocumentNode.SelectNodes("//table//tr");
Get all cells from the rows (notice the dot at the beginning of the expression - it means it will only search in the containing node):
if (rows != null && rows.Count > 0)
{
    foreach (var row in rows)
    {
        var cells = row.SelectNodes(".//td");
    }
}
Get the inner text from a cell:
var title = cells[0].InnerText;
Get a single node:
var link = cells[1].SelectSingleNode(".//a");
Get an attribute from a node (in this case the link’s destination):
if (link != null)
{
    var href = link.GetAttributeValue("href", string.Empty);
}
Get a div by ID:
var div = html.DocumentNode.SelectSingleNode("//div[@id='myid']");
Get a div with a specific class:
var div = html.DocumentNode.SelectNodes("//div[@class='myclass']");
Get a div which contains a class:
var div = html.DocumentNode.SelectNodes("//div[contains(@class, 'content')]");
Get a div which does not have a specific class:
var div = html.DocumentNode.SelectNodes("//div[not(@class='hidden')]");
Get all links from a specific div:
var links = html.DocumentNode.SelectNodes("//div[@id='main']//a");
Get the last link on a specific div:
var lastLink = html.DocumentNode.SelectSingleNode("//div[@id='main']//a[last()]");
Get the second table in the document:
var table = html.DocumentNode.SelectSingleNode("//table[2]");
Get a table with a specific class and a specific text in the header:
var main = html.DocumentNode.SelectSingleNode("//table[contains(@class, 'standings') and .//th//text()[contains(., 'Full Table')]]");

A Simple Example of Web Scraping With the Html Agility Pack

using System;
using System.Linq;
using HAP=HtmlAgilityPack;

namespace DemoHtmlAgilityPack
{
    class Program
    {
        private static void Main(string[] args)
        {
            using (var client = new System.Net.WebClient())
            {
                var filename = System.IO.Path.GetTempFileName();

                client.DownloadFile("http://python.org", filename);

                var doc = new HAP.HtmlDocument();
                doc.Load(filename);

                var root = doc.DocumentNode;

                var a_nodes = root.Descendants("a").ToList();

                foreach (var a_node in a_nodes)
                {
                    Console.WriteLine();
                    Console.WriteLine("LINK: {0}", a_node.GetAttributeValue("href",""));
                    Console.WriteLine("TEXT: {0}", a_node.InnerText.Trim());
                }
            }

            Console.ReadKey();
        }
    }
}
Not hard at all!

Using HtmlAgilityPack to manipulate and read img src’s

HtmlAgilityPack is a cool library that allows developers to download an html document from the web and read it’s content, it also supports linq to objects.
If you are going to use this library I suggest you download it directly from Nuget.
Lets make an example of how you can get all image nodes with agility pack…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
static void Main(string[] args)
{
    //WebClient to download page
    var client = new WebClient();
    string html = client.DownloadString("http://www.christianjvella.com/wordpress/");
    //load string to AgilityPack document
    var document = new HtmlDocument();
    document.LoadHtml(html);
    //document.DocumentNode.SelectNodes("//img") - this will return all nodes which are <img /> including their attributes
    foreach (var image in document.DocumentNode.SelectNodes("//img"))
    {
 
        var src = image.GetAttributeValue("src", null);
        var altText = image.GetAttributeValue("alt", null);
 
        //if you want you can save the image to a stream or to a file
        //you can also manipulate the attributes - in this case I am changing the src
        image.SetAttributeValue("src", "newimageuri.com/image.jpg"); //set the src to point to the new src
    }
    //write the new html
    Console.Write(document.DocumentNode.OuterHtml);
    Console.ReadLine();
}
In this C# example we are creating a WebClient to download the HTML as Text/String, then we are loading the text into an agility document and we are getting the “img” nodes and doing something with them
If you want to download the Image Stream or file use one of these methods and call it after you get the src, sometimes we need to add the Website Url to the src in order to download it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static void SaveImageToDrive(string src)
{
    const string localFilename = @"c:\file.jpg";
    using (var client = new WebClient())
    {
        client.DownloadFile(src, localFilename);
    }
}
 
public static Stream SaveImageToStream(string src)
{
    var client = new WebClient();
    var stream = client.OpenRead(src);
    return stream;
}