Alper Konuralp

Kartınızı Oluşturun
Google+
Follow @alperkonuralp

Posts Tagged ‘C#’

Entity Framework 4.1 Code First, using Enum Types

When I use a enum type to my Entity Framework 4.1 Code First project, I noticed that the generated database table column (which is my enum type column),  type is nvarchar(max). But I want to that to be tinyint type. So, here is my solution ;

This is the enum type that i use:

    public enum FileTypesEnum : byte
    {
        DataSheet = 1,
        ProductManual = 2,
        Driver = 3,
        Software = 4,
        Image = 5,
        Video = 6
    }

And the property of the poco class :

    [Required]
    [Column("FileType", Order = 2)]
    public FileTypesEnum FileType { get; set; }

but it doesn’t work as i want it to be.
So, i came up with this :

    [Required]    
    [Column("FileTypeValue", Order = 2)]    
    public byte FileTypeValue { get; set; }     
    [NotMapped]    
    public FileTypesEnum FileType     {     
        get { return (FileTypesEnum)FileTypeValue; }        
        set { FileTypeValue = (byte)value; }    
    }

Enjoy!

SelectListItem Class for Web Applications and MVC Applications at ASP.NET

I am developing to new web site with ASP.NET MVC 3. Therefore I need a SelectListItem class for ajax operations. So i wrote a new generic class. In case you guys need it i thought I’d share it.

 

using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace WebSite.Models.ViewEntities
{
    /// <summary>
    /// Select List Item Entity
    /// </summary>
    /// <typeparam name="T">Text Property Type</typeparam>
    /// <typeparam name="U">Value Property Type</typeparam>
    [JsonObject]
    public class SelectListItem<T, U>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectListItem&lt;T, U&gt;"/> class.
        /// </summary>
        public SelectListItem()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SelectListItem&lt;T, U&gt;"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        public SelectListItem(T text)
        {
            Text = text;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SelectListItem&lt;T, U&gt;"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="value">The value.</param>
        public SelectListItem(T text, U value)
        {
            Text = text;
            Value = value;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SelectListItem&lt;T, U&gt;"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="value">The value.</param>
        /// <param name="isSelected">if set to <c>true</c> [is selected].</param>
        public SelectListItem(T text, U value, bool isSelected)
        {
            Text = text;
            Value = value;
            IsSelected = isSelected;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>
        /// The value.
        /// </value>
        [JsonProperty]
        public U Value { get; set; }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        [JsonProperty]
        public T Text { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is selected.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is selected; otherwise, <c>false</c>.
        /// </value>
        [JsonProperty]
        public bool IsSelected { get; set; }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            var builder = new StringBuilder();
            builder.Append("{ Value = ");
            builder.Append(Value);
            builder.Append(", Text = ");
            builder.Append(Text);
            builder.Append(", IsSelected = ");
            builder.Append(IsSelected);
            builder.Append(" }");
            return builder.ToString();
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="value">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object value)
        {
            var type = value as SelectListItem<T, U>;
            return (type != null) && EqualityComparer<U>.Default.Equals(type.Value, Value) && EqualityComparer<T>.Default.Equals(type.Text, Text) && EqualityComparer<bool>.Default.Equals(type.IsSelected, IsSelected);
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
        /// </returns>
        public override int GetHashCode()
        {
            var num = 0x7a2f0b42;
            num = (-1521134295 * num) + EqualityComparer<U>.Default.GetHashCode(Value);
            num = (-1521134295 * num) + EqualityComparer<T>.Default.GetHashCode(Text);
            return (-1521134295 * num) + EqualityComparer<bool>.Default.GetHashCode(IsSelected);
        }
    }
}

WCF asenkron metod çağırımı

Yunus Emre sormuş :

WCF  deki fonksiyonların asenkron  çalışmasını nasıl sağlayabiliriz
arkadaşlar?bilgisi olan var mı bu konuda ?

Şu an yazdığım fonksiyonların içinde thread.Sleep(60000) ile 1 dk
bekletiyorum ve time out a düşüyor (istisna alıyorum).

Benim cevabım :

Client tarafını hazırlarken asenkron metodların oluşturulmasını sağlaman gerekli ancak ondan sonra kullanabilirsin. Ayrıca o sistemin asenkron olayı için 2 yönlü (two way) bir çalışma yapmak gerekebilir.

Disposable nesneler

Özer şöyle bir soru sormuş :

Genel olarak arraylist lerde dispose metodunu kullanıyorum. Direk ramlerde dizilim yaptığı için ya da daha insan aklında görselleştirilebilir birşey olduğundan mıdır bilmem noktadan sonra hiç düşünmeden yazıyorum Dispose u metodumu kapatırken. Ancak bunu neden veritabanı bağlantı metodlarında kullanmayalım ki? Şimdiye kadar çalıştığım ajanslarda dahil bütün kütüphanelerde close olarak kapatılıyor veritabanı bağlantıları. Sonuçta kullanıcı butona tıklar arkadan çağrılır metodlar. Kendi kafasına göre mi takılıyor bu metodlar?! Ne gerek var Ramlerde sürekli  durmasına. İşi bitince temizlesin geçsin işte. Olmaz mı?!

Cevap olarak bende şunu söyledim :

bunun en kolay yolu using kullanmak. Ki zaten ben bütün kodları böyle yazıyorum. :D Örnek olarak :

using( SqlConnection sc = new  SqlConnection("Data Source=.....")
{
    SqlCommand scom = new  SqlCommand("SELECT * FROM ....", sc);
    sc.Open();

    SqlDataReader sdr = scom.ExecuteReader();

    // .........

}

using bloğu bittiği anda sc için dispose metodu çalıştırılır. ayrıca bu bir blok olduğu için blok bittiğinde içte tanımlanan ve dışarıya aktarılmayan bütün elemanlar temizlenir.

Using’i bütün disposable sınıflar için kullanmak mümkün. Örneğin:
FileStream
MemoryStream
Bitmap
….

Version Upgrader

Sizde benim gibi versiyon takibi için sürekli assembly.cs dosyasının yolunu tutuyorsanız, benim bu işe bir son vermek amacıyla yazmış olduğum aşağıdaki küçük programcığı kullanmaya başlayabilirsiniz. Amacım parametrede belirtilen dizin ve bütün alt dizinlerindeki assembly.cs dosyalarını bulup, içlerindeki versiyon bilgisinin revision değerini bir arttırmak. İşinize yaraması dileğimle.

Çalışan Versiyonunu indir

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace VersionUpgrader
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Lütfen arama yapılacak dizini giriniz.");
                return;
            }

            string dizin = args[0];

            var di = new DirectoryInfo(dizin);

            if (di.Exists)
            {
                Console.WriteLine("VersionUpgrader is searching at {0}.", di.FullName);
                FindDirectory(di);
                Console.WriteLine("VersionUpgrader search finished at {0}.", di.FullName);
            }
            else
            {
                Console.WriteLine("Girmiş olduğunuz dizin bulunamadı.");
                return;
            }
        }

        private static readonly Regex rx1 =
            new Regex(
			@"\[assembly: AssemblyVersion\(\""([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\""\)\]",
			RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
        private static readonly Regex rx2 =
            new Regex(
			@"\[assembly: AssemblyFileVersion\(\""([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\""\)\]",
			RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private static void FindDirectory(DirectoryInfo di)
        {
            var fid = di.GetFiles("AssemblyInfo.cs");

            if (fid.Length > 0)
            {
                foreach (FileInfo info in fid)
                {
                    var s = File.ReadAllText(info.FullName);

                    var changed = new StringBuilder();

                    s = rx1.Replace(s, x =>
                    {
                        changed.AppendFormat(
						    "AssemblyVersion(\"{0}.{1}.{2}.{3}\" => \"{0}.{1}.{2}.{4}\")",
                            x.Groups[1].Value,
                            x.Groups[2].Value,
                            x.Groups[3].Value,
                            x.Groups[4].Value,
                            (int.Parse(x.Groups[4].Value)) + 1);

                        return string.Format(
                            "[assembly: AssemblyVersion(\"{0}.{1}.{2}.{3}\")]",
                            x.Groups[1].Value,
                            x.Groups[2].Value,
                            x.Groups[3].Value,
                            (int.Parse(x.Groups[4].Value)) + 1);
                    });

                    s = rx2.Replace(s, x =>
                    {
                        if (changed.Length > 0)
                        {
                            changed.Append(" , ");
                        }
                        changed.AppendFormat(
						    "AssemblyFileVersion(\"{0}.{1}.{2}.{3}\" => \"{0}.{1}.{2}.{4}\")",
                            x.Groups[1].Value,
                            x.Groups[2].Value,
                            x.Groups[3].Value,
                            x.Groups[4].Value,
                            (int.Parse(x.Groups[4].Value)) + 1);

                        return string.Format(
                            "[assembly: AssemblyFileVersion(\"{0}.{1}.{2}.{3}\")]",
                            x.Groups[1].Value,
                            x.Groups[2].Value,
                            x.Groups[3].Value,
                            (int.Parse(x.Groups[4].Value)) + 1);
                    });

                    if (changed.Length > 0)
                    {
                        s = string.Format(
						    "{0}\r\n// This file changed by VersionUpgrader at {1:G} << {2} >>",
							s, DateTime.Now, changed);
                    }

                    File.WriteAllText(info.FullName, s);

                    Console.WriteLine("{0} is changed.", info.FullName);
                }
            }

            var did = di.GetDirectories();

            if (did.Length <= 0) return;

            foreach (DirectoryInfo dii in did)
            {
                FindDirectory(dii);
            }
        }
    }
}
İzmir Yazılım Grubu
Google Groups
Subscribe to İzmir Yazılım Grubu
Email:
Visit this group
Mayıs 2012
Pts Sal Çar Per Cum Cts Paz
« Şub    
 123456
78910111213
14151617181920
21222324252627
28293031  
Yeni Downloadlar
StatPress
Visits today: 98
Sahip oldugum diger adresler :
3dmaxtraining.info
3dmaxtrainings.com
3dmaxtrainings.info
adobelearning.info
adobelearnings.info
adobetrainings.com
adobetrainings.info
autocadbootcamp.info
autocadexams.info
autodesklearning.info
autodesklearnings.com
autodesklearnings.info
ciscotrainings.info
egepro.com
elonunbahcesi.com
elonunbahcesi.info
flashbootcamp.info
flashexams.com
flashexams.info
konuralp.biz
konuralp.org
mayatutorial.info
mayatutorials.info
microsoftexams.info
microsofttrainings.info
proege.com
sharepointlearning.info
sharepointlearnings.com
sharepointlearnings.info
sharepointtutorial.info
silverlightbootcamp.info
silverlightlearning.info
silverlightlearnings.info
silverlighttraining.info
silverlighttrainings.com
silverlighttrainings.info
silverlighttutorial.info
silverlighttutorials.info
sirasende.info
urunbul.info
yagmurca.com
yagmurca.info