Archive for the 'c#' category

Guid() den daha kısa uniqe id

Ara 13 2011 Published by under c#

Kayıt içerisinde tekil id için kullanılan guid in uzun olduğunu düşünüyorsanız, onun yerine aşağıdaki fonksiyonu kullanın, ama üretilen sayı/harf silsilesi ne kadar uzun olsada çok düşük ihtimallede olsa tekil olmayacaktır, o yüzden yinede kayıt sırasında kontrol edilmesi gerekir. Alıntı yaptığım sayfa bitly yada goo.gl gibi kısaltma url projesi için hazırlanmış.

 

        private static string shorturl_chars_lcase = "abcdefgijkmnopqrstwxyz";
        private static string shorturl_chars_ucase = "ABCDEFGHJKLMNPQRSTWXYZ";
        private static string shorturl_chars_numeric = "23456789";

        public static string RandomCharacters(int feedCount)//feedCount burada tekil kodun uzunluğu
        {
            // Create a local array containing supported short-url characters
            // grouped by types.
            char[][] charGroups = new char[][]
            {
                shorturl_chars_lcase.ToCharArray(),
                shorturl_chars_ucase.ToCharArray(),
                shorturl_chars_numeric.ToCharArray()
            };

            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)
                charsLeftInGroup[i] = charGroups[i].Length;

            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)
                leftGroupsOrder[i] = i;

            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same "random" number within a
            // second), we will use a random number generator to seed the
            // randomizer.

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                        randomBytes[1] << 16 |
                        randomBytes[2] << 8 |
                        randomBytes[3];

            // Now, this is real randomization.
            Random random = new Random(seed);

            // This array will hold short-url characters.
            char[] short_url = null;

            // Allocate appropriate memory for the short-url.
            short_url = new char[random.Next(feedCount, feedCount)];

            // Index of the next character to be added to short-url.
            int nextCharIdx;

            // Index of the next character group to be processed.
            int nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int lastCharIdx;

            // Index of the last non-processed group.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

            // Generate short-url characters one at a time.
            for (int i = 0; i < short_url.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (lastLeftGroupsOrderIdx == 0)
                    nextLeftGroupsOrderIdx = 0;
                else
                    nextLeftGroupsOrderIdx = random.Next(0,
                                                         lastLeftGroupsOrderIdx);

                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                    nextCharIdx = 0;
                else
                    nextCharIdx = random.Next(0, lastCharIdx + 1);

                // Add this character to the short-url.
                short_url[i] = charGroups[nextGroupIdx][nextCharIdx];

                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)
                    charsLeftInGroup[nextGroupIdx] =
                                              charGroups[nextGroupIdx].Length;
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];
                        charGroups[nextGroupIdx][lastCharIdx] =
                                    charGroups[nextGroupIdx][nextCharIdx];
                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]--;
                }

                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                        leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                    leftGroupsOrder[nextLeftGroupsOrderIdx];
                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx--;
                }
            }

            // Convert password characters into a string and return the result.
            return new string(short_url);
        }

http://www.java-frameworks.com/csharp/shorturldotnet/ShortUrl.Utils.cs.html

No responses yet

Linqtosql Transaction İşlemi

Kas 15 2011 Published by under c#

 

Product prod = q.Single(p => p.ProductId == 15);

if (prod.UnitsInStock > 0)
   prod.UnitsInStock--;

db.Transaction = db.Connection.BeginTransaction();
try {
   db.SubmitChanges();
   db.Transaction.Commit();
}
catch {
   db.Transaction.Rollback();
   throw;
}
finally {
   db.Transaction = null;
}

 

No responses yet

C# Projesi OutlookBridgeFBF

Tem 02 2011 Published by under c#, proje

2010 da meraktan yazdığım, outlook ile senkronize çalışan windows mobile 6.5 telefonumdaki kişilerin birçoğunun fotoğraflarını facebook arkadaş listemden alıp, outlook’uma kayıt etmeme yarayan programcık, böylelikle telefonu senkronize ettiğimde arayan/aranan kişinin resmini de görmemi sağlıyordu.

http://www.tiravoglu.com/index.php/c-ta-web-sayfasindaki-resmi-image-olarak-cekme/

http://www.tiravoglu.com/index.php/c-la-facebook-uygulamasi-ve-arkadas-resimlerine-ulasmak/

http://www.tiravoglu.com/index.php/c-la-outlooktaki-kisilerin-resimlerine-ulasin/

http://www.tiravoglu.com/index.php/c-la-outlooktaki-kisilerin-resimlerini-degistirin/

outlookbridgefbf

Sol tarafta Facebook arkadaş listesindeki kişiye tıklayıp ardından sağ tarafta o kişin outlook ismine tıklayıp, butona basınca facebook resmini bilgisayara indirip ardından outlooktaki resmini silip yerine facebooktan indirdiği resmi kayıt ediyor.

No responses yet

C# la Outlook’taki kişilerin resimlerini değiştirin

Tem 02 2011 Published by under c#

Listview’de listelenmiş Outlook kişilerden seçili olanın resmini değiştirmek için; (listView1′de facebook arkadaş listesindekilerin resimleri listView2′de ise outlook kişilerdeki kayıtlı kişilerin resimleri var, aşağıdaki kodlar, listView1′de ki resmi alıp, listView2 ‘de seçili olan outlook kişinin resmi olarak kayıt eder)

using Outlook = Microsoft.Office.Interop.Outlook;
Outlook._Application outobj;
Outlook.MAPIFolder fldContacts;
Microsoft.Office.Interop.Outlook.ContactItem contact;
 if (listView2.SelectedItems.Count == 1 && listView1.SelectedItems.Count == 1)
            {

                contact = (Microsoft.Office.Interop.Outlook.ContactItem)fldContacts.Items[listView2.SelectedItems[0].Index + 1];
                if (contact.HasPicture)
                {
                    contact.RemovePicture();

                }

                Image _Image = null;
                _Image = DownloadImage(friends[listView1.SelectedItems[0].Index].pic);

                if (_Image != null)
                {

                    _Image.Save(@"C:\outlookbridgefb" + listView1.SelectedItems[0].Index + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                contact.AddPicture(@"c:\outlookbridgefb" + listView1.SelectedItems[0].Index + ".jpg");
                contact.Save();
                try
                {
                    System.IO.File.Delete(@"c:\outlookbridgefb" + listView1.SelectedItems[0].Index + ".jpg");
                }
                catch
                {

                }

               // outlookkontaktdoldur();

            }

Outlookta’ki kişilerin resimlerine nasıl ulaşırım diyorsanız -> C# la Outlook’taki kişilerin resimlerine ulaşın

One response so far

C# la Facebook uygulaması ve arkadaş resimlerine ulaşmak

Tem 02 2011 Published by under c#

Facebook api kullanarak yazdığınız uygulamanın, o uygulamayı kullanan kişinin arkadaşlarının resimlerine ulaşması için aşağıdaki koda bi göz atın.  Facebook arkadaşlarının resimlerini ListView içerisinde arkadaş adı ile birlikte gösterir.

https://www.facebook.com/developers/createapp.php bu adresten yeni bir uygulama oluşturup, aşağıdaki “API Anahtarı” yazan yere yeni uygulamanın api anahtarını yazın. Continue Reading »

2 responses so far

C# la Outlook’taki kişilerin resimlerine ulaşın

Tem 02 2011 Published by under c#

Outlook’taki  kişilerin resimlerini görmek ve ListView’in içine doldurmak için;

using Outlook = Microsoft.Office.Interop.Outlook;
Outlook._Application outobj;
Outlook.MAPIFolder fldContacts;
Microsoft.Office.Interop.Outlook.ContactItem contact;
listView2.Clear();
            ımageList2.Images.Clear();
            outobj = new Outlook.Application();
            fldContacts = (Outlook.MAPIFolder)outobj.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            int sira2 = 0;

            listView2.LargeImageList = ımageList2;
            foreach (Outlook._ContactItem kontakt in fldContacts.Items)
            {
                if (kontakt.HasPicture)
                {
                    contact = (Microsoft.Office.Interop.Outlook.ContactItem)kontakt;
                    ımageList2.Images.Add(sira2.ToString(), Image.FromFile(GetContactPicturePath(contact)));

                }
                listView2.Items.Add(new ListViewItem(kontakt.FullName, sira2.ToString()));
                sira2 = sira2 + 1;
            }
public static string GetContactPicturePath(Microsoft.Office.Interop.Outlook.ContactItem contact)
        {
            return GetContactPicturePath(contact, System.IO.Path.GetTempPath());
        }

        public static string GetContactPicturePath(Microsoft.Office.Interop.Outlook.ContactItem contact, string path)
        {
            string picturePath = "";
            if (contact.HasPicture)
            {
                foreach (Microsoft.Office.Interop.Outlook.Attachment att in contact.Attachments)
                {
                    if (att.DisplayName == "ContactPicture.jpg")
                    {
                        try
                        {
                            picturePath = System.IO.Path.GetDirectoryName(path) + "\\Contact_" + contact.EntryID + ".jpg";
                            if (!System.IO.File.Exists(picturePath))
                                att.SaveAsFile(picturePath);
                        }
                        catch
                        {
                            picturePath = "";
                        }
                    }
                }
            }
            return picturePath;
        }

not:kodlar 2010 ve öncesine aittir, yeni yöntemler çıkmış olabilir.

One response so far

C# ta web sayfasındaki resmi Image olarak çekme.

Tem 02 2011 Published by under c#

Önceden C# ta web sayfasındaki resmi Bitmap olarak çekme ‘yi paylaşmıştım. Nette bu kodun Image nesne olarak çeken halini buldum.

public Image DownloadImage(string _URL)
        {
            Image _tmpImage = null;

            try
            {
                // Open a connection
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

                _HttpWebRequest.AllowWriteStreamBuffering = true;

                // You can also specify additional header values like the user agent or the referer: (Optional)
                _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                _HttpWebRequest.Referer = "http://www.google.com/";

                // set timeout for 20 seconds (Optional)
                _HttpWebRequest.Timeout = 20000;

                // Request response:
                System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

                // Open data stream:
                System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

                // convert webstream to image
                _tmpImage = Image.FromStream(_WebStream);

                // Cleanup
                _WebResponse.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                return null;
            }

            return _tmpImage;
        }

kullanımıda böyleymiş.

// Download web image
Image _Image = null;
_Image = DownloadImage("http://www.yourdomain.com/sample-image.jpg");

// check for valid image
if (_Image != null)
{
    // show image in picturebox
    pictureBox1.Image = _Image;

    // lets save image to disk
    _Image.Save(@"C:\SampleImage.jpg");
}

kaynak: http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Download-Image-from-URL.html

 

One response so far

C# ta İki Tarih Arasındaki Toplam Ay Sayısı

Haz 25 2011 Published by under c#

Görünen oki C# ta iki tarih arasındaki toplam ay sayısını bulabilmenin en kolay yöntemi aşağıdaki yöntem olsa gerek.

 int ayFarki = 0;

if (tarih2.Month < tarih1.Month)
{
        ayFarki = (tarih2.Month + (12 * (tarih2.Year - tarih1.Year))) - tarih1.Month;
}
else
{
        ayFarki = (tarih1.Month - tarih2.Month) + (12 * (tarih2.Year - tarih1.Year));
}

Daha kolay yöntemini bilen varsa lütfen yazsın.

2 responses so far

C# ta web sayfasındaki resmi Bitmap olarak çekme.

Haz 21 2011 Published by under c#

Web sayfasında ki resmi kendi mü/web uygulamanızda Bitmap tipinde kullanabilmek için aşağıdaki kod işinizi görecektir.

	public static Bitmap ResimOku(string Adres)
        {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Adres);
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
                myResponse.Close();
                return bmp;
        }

“Adres” değişkenini full url olarak kullanmanız gerekmektedir.
ResimOku(“http://www.tiravoglu.com/istediğiniz_resim.jpg”) şeklinde.

One response so far

C# la txt dosyasından yada web sayfasından eposta yakalama/ayıklama

Haz 21 2011 Published by under c#

Verilen dosya içindeki epostaları yakalayıp başka bir txt dosyasına yazan kodlar

            string okunacak_txt=@"c:\oku.txt";
            string yazilacak_txt = @"c:\yaz.txt";
            string data = File.ReadAllText(okunacak_txt);
            Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
            MatchCollection emailMatches = emailRegex.Matches(data);
            StringBuilder sb = new StringBuilder();
            foreach (Match emailMatch in emailMatches)
            {
                sb.AppendLine(emailMatch.Value + Environment.NewLine);
            }
            File.WriteAllText(yazilacak_txt, sb.ToString());

Aynı şekilde istenirse txt dosyadan okumak yerine websitesi içerisinden okuma yapılabilir.


        WebClient w = new WebClient();
        w.Encoding = System.Text.Encoding.UTF8;
        string s = w.DownloadString("http://www.tiravoglu.com");
        string yazilacak_txt = @"c:\yaz.txt";
        string data = s;
        Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
        MatchCollection emailMatches = emailRegex.Matches(data);
        StringBuilder sb = new StringBuilder();
        foreach (Match emailMatch in emailMatches)
        {
            sb.AppendLine(emailMatch.Value + Environment.NewLine);
        }
        File.WriteAllText(yazilacak_txt, sb.ToString());

No responses yet

Older posts »