صفحه 3 از 14 اولاول 1234513 ... آخرآخر
نمایش نتایج 81 تا 120 از 533

نام تاپیک: 1001 نکته در سی شارپ

  1. #81

    سیاه و سفید کردن عکس با کد نویسی

    < نمونه برنامه را می تونین در آخر مطالب دریافت کنید>

    توسط متد زیر می توانید هر عکسی را به حالت سیاه و سفید یا همون grayScale در بیارین



    public Image GrayScaleImage(Graphics graph, Image img, int left, int top)
    {

    ColorMatrix colorMix = new ColorMatrix();
    colorMix.Matrix00 = 1 / 3f;
    colorMix.Matrix01 = 1 / 3f;
    colorMix.Matrix02 = 1 / 3f;
    colorMix.Matrix10 = 1 / 3f;
    colorMix.Matrix11 = 1 / 3f;
    colorMix.Matrix12 = 1 / 3f;
    colorMix.Matrix20 = 1 / 3f;
    colorMix.Matrix21 = 1 / 3f;
    colorMix.Matrix22 = 1 / 3f;

    ImageAttributes imgAttrib = new ImageAttributes();
    imgAttrib.SetColorMatrix(colorMix);


    graph.DrawImage(img, new Rectangle(left, top, img.Width,
    img.Height), 0, 0, img.Width, img.Height,
    GraphicsUnit.Pixel, imgAttrib);
    Bitmap bmp = new Bitmap(img);
    return bmp;


    }




    عملکر متد خیلی واضحه.
    کلا با ImageAttribute ها و ColorMiser ها خیلی کارهای خوشکلی میشه کرد که به مرور میذارم اینجا
    راستی این کد به درد اون دسته عزیزانی که می خواستن، shutdown ویندوز را شبیه سازی کنند خیلی خوبه. (اینکه می خواستن از دسکتاپ عکس بگیرن و بعد اونو تار کنن) البته برای تار کردن عکس ها، راه های دیگه ای هم هست که انشالا به مرور
    نمونه






    در حاشیه :
    تورو خدا می بینین؟ فردا ظهر امتحان ارشد دارم، الان ساعت 1:30 نصف شبه نشستم برای شما و فقط به عشق شما دوستان مطلب می نویسم
    موفق باشید
    یا علی مدد
    مهدی کیانی
    فایل های ضمیمه فایل های ضمیمه
    آخرین ویرایش به وسیله Mahdi.Kiani : پنج شنبه 02 اسفند 1386 در 01:14 صبح دلیل: یادم رفته بود نمونه برنامه را آپ کنم

  2. #82

    کار کردن با کلاس TimeZoneInfo

    این کلاس مختص دات نت 3.5 (به بعد) است و جهت استفاده باید System.Core رو نیز به References پروژه ی خود بیافزایید.

    مثال - بدست آوردن تاریخ و زمان فعلی در توکیو :
    TimeZoneInfo tzSource = TimeZoneInfo.Local;
    TimeZoneInfo tzDestination = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
    string sourceTime = TimeZoneInfo.ConvertTime(DateTime.Now,
    tzSource, tzDestination).ToShortTimeString();
    MessageBox.Show(sourceTime);

  3. #83

    بدست آوردن لیست تمامی ناحیه های زمانی (Time Zone)

    این روش مختص دات نت 3.5 (به بعد) است.

    using System.Collections.ObjectModel;
    بدست آوردن Id و DisplayName نواحی :
    ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
    foreach (TimeZoneInfo zone in zones)
    {
    listBox1.Items.Add(zone.Id);
    listBox2.Items.Add(zone.DisplayName);
    }

  4. #84

    انجام عملیات متداول روی فایلها و دایرکتوریها

    using System.IO;


    //To create a directory
    Directory.CreateDirectory(@"C:\MyNewDir");

    //To move a directory
    Directory.Move(@"C:\MyNewDir", @"C:\MyMovedDir");

    //To delete a directory
    Directory.Delete(@"C:\MyMovedDir");

    //To Delete a directory recursively
    Directory.Delete(@"C:\MyNewDir", true);

    //To Delete a File
    File.Delete(@"C:\MyFile.Txt");

    //To Move a File
    File.Move(@"C:\MyFile.Txt", @"C:\MyOtherDir\MyFile.Txt");

    //To Copy a file
    File.Copy(@"C:\MyFile.Txt", @"C:\MyOtherDir\MyFile.Txt");

    //To copy to a different file name is also possible
    File.Copy(@"C:\MyFile.Txt", @"C:\MyOtherDir\MyNewFileName.Txt");

    //To get information about a file, like the length
    //You can also get the extension, directory, LastAccessedtime,
    //LastModifiedTime, wether the file exists or not, the creation date,
    //attributes of the file etc, from the FileInfo class
    FileInfo FI = new FileInfo(@"C:\MyFile.Txt");
    Console.WriteLine("File size of MyFile.Txt: {0}", FI.Length);

    //copy example
    String DateTemp = DateTime.Now;
    File.Copy(@"P:\PRD\Products\AHM\prod.CD\Database\d ata.mdb",
    @"P:\PRD\Products\AHM\prod.CD\Database\"+ DateTemp +"-data.mdb");
    منبع : http://www.eggheadcafe.com/community...in-folder.aspx

  5. #85

    معنای کلمات متداولی که میشنوید

    معنای کلمات متداولی که معمولا دات نت کار ها خواهند شنید. مخصو.صا تازه کار های عزیز

    1 ) CLR
    مخفف : Common Language RunTime

    معنا :
    محیط زمان اجرای برنامه های دات نت
    -------------------------------------------------------------------------
    2) CTS
    مخفف : Common Type System
    معنا : تایپ هایی هستند که در همه زبان های دات نت شناخته شده هستند و معمولا یک نام مستعار در هر زبان مجزا دارند.
    مثلا System.Int32 در زبان C#‎‎‎‎‎ همان int و در زبان VB همان Integer است.
    نکته:
    CTS تایپ ها برای همانهنگ سازی بین زبان های مختلف دات نتی استفاده میشه
    ----------------------------------------------------------------------------------------------
    3) IL
    مخفف : Intermediate Language
    معنا : زبان واسطی که در مرحله اول کامپیا برنامه ها، تمامی کد های نوشته شده با زبان های دات نت (اعم از سی شارپ، وی بی و ..) به این زبان ترجمه می شوند. (باز هم جهت سازگاری بین زبان های مختلف در دات نت)

    مثال

    تکه کدی به زبان C#‎‎‎‎‎


    public int add(int num1, int num2)
    {

    return num1 + num2;
    }




    همان تکه کد به زبان VB


    Public Function add(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

    Return num1 + num2
    End Function




    تکه کد فوق به زبان IL


    .method public hidebysig instance int32 add(int32 num1, int32 num2) cil managed
    {
    .maxstack 2
    .locals init (
    [0] int32 CS$1$0000)
    L_0000: nop
    L_0001: ldarg.1
    L_0002: ldarg.2
    L_0003: add
    L_0004: stloc.0
    L_0005: br.s L_0007
    L_0007: ldloc.0
    L_0008: ret
    }





    نکته : شما می توانید کل برنامه خود را به زبان IL بنویسید و سپس آن را اجرا کنید. ولی اصولا هیچ آدم عاقلی این کار را نمیکنه
    ------------------------------------------------------------------------------------------
    4 ) CIL
    مخفف : Common Intermediate Langiage
    معنا : معالد همون IL هست.
    نکته: استفاده از IL متداول تر است.
    -----------------------------------------------------------------------------------------
    5) VES
    مخفف : Virtual Executation Systeme
    معنا : معادل CLR هست
    نکته: CLR متداول تر است.
    ---------------------------------------------------------------------------------
    6) CLI
    مخفف : Common Language Interface
    معنا : به مجموعه CLR و CTS و CLI می گویند

    فعلا همینا تو ذهنم بود
    اگه بازم یادم اومد، همین جا میذارم

    موفق باشید
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:29 عصر

  6. #86

    کپی کردن فایلهای درون یک دایرکتوری (فقط فایلها)

    using System.IO;
    فایلها را در مسیرC:\CopiedFolder کپی میکند :
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.Description = "Find Folder to Copy.";
    if (fbd.ShowDialog() == DialogResult.OK)
    {
    string[] files = Directory.GetFiles(fbd.SelectedPath);
    Directory.CreateDirectory(@"C:\CopiedFolder");
    for (int i = 0; i < files.Length; i++)
    {
    string tmpFileExt = Path.GetExtension(files[i]);
    string tmpFileName = Path.GetFileNameWithoutExtension(files[i]);
    File.Copy(files[i], @"C:\CopiedFolder\" + tmpFileName + tmpFileExt, true);
    }
    }

    منبع : http://www.se7ensins.com/forums/c/84...g-folders.html

  7. #87

    Lightbulb (Windows Presentation Foundation (WPF چیست ؟

    نسل جدید ساخت UI است که با پیدایش دات نت فریمورک 3.0 بوجود آمد.
    با استفاده از زبان XAML باعث تفکیک و جدایی ظاهر یک فرم و منطق پشت زمینه ی آن میشود، لذا برنامه نویس و گرافیست میتوانند در کنار یکدیگر به راحتی روی یک برنامه کار کنند.

    قبلا برای ساخت یک برنامه که قابلیتهایی مانند :
    Graphical interface, On-screen documents, Fixed-format documents, Video and audio, 2D/3D graphics, Image Processing داشته باشد؛‌ میبایستا کتابخانه های مختلفی مانند :
    DirectX, +GDI, PDF, Media Player, Windows Form, ... را میشناختید و با آنها کار میکردید؛ در حالیکه هم اکنون تنها با استفاده از WPF تمامی آن قابلیتها در دسترس هستند.

    پیشنهاد میکنم حتما لینک بسیار مفید زیر رو ببینید :
    http://msdn2.microsoft.com/en-us/library/aa970268.aspx

    این هم خوبه :
    http://en.wikipedia.org/wiki/Windows...ion_Foundation

  8. #88

    کپی کامل یک دایرکتوری و تمامی زیرشاخه های آن بصورت بازگشتی

    using System.IO;
    void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
    {
    if (!destination.Exists)
    destination.Create();
    // Copy all files.
    FileInfo[] files = source.GetFiles();
    foreach (FileInfo file in files)
    file.CopyTo(Path.Combine(destination.FullName, file.Name));

    // Process subdirectories.
    DirectoryInfo[] dirs = source.GetDirectories();
    foreach (DirectoryInfo dir in dirs)
    {
    // Get destination directory.
    string destinationDir = Path.Combine(destination.FullName,dir.Name);
    // Call CopyDirectory() recursively.
    CopyDirectory(dir, new DirectoryInfo(destinationDir));
    }
    }
    منبع - کتاب : Visual C#‎ 2005 Recipes: A Problem-Solution Approach

  9. #89

    Lightbulb سریالیزشین چیست ؟

    Serialize :
    فرآیندی برای تبدیل یک آبجکت و یا گرافی متشکل از چند آبجکت به یک حالت خطی (و جریان وار) از بایت ها برای انتقال و یا ذخیره سازی در محلی دیگر است.

    Deserialize :
    عمل برعکس سریالیزشین است؛ یعنی دوباره ساختن آبجکت از روی جریانی از بایتها .


    انواع فرمت ها در سریالیزشین :
    1- Binary : بصورت باینری سریالایز میکند. (فشرده ترین و efficient ترین حالت است)
    SOAP -2 : بصورت soap سریالایز میکند. (برای ارسال در شبکه و جایی که از تحت دات نت بودن کلاینتها مطمئن نیستیم)
    XML -3 : بصورت xml سریالایز میکند. (برای ارسال تحت شبکه - مزیت : خوانایی)

    برخی از موارد کاربرد سریالزیشین:
    1- کپی یک انشعاب از آبجکتها
    2- انتقال اطلاعات در شبکه
    3- نگهداری state ها و snapshot های مختلف در یک برنامه (برای موارد حساس : مثل تراکنشهای بانکی و ...)
    4- پیاده سازی Deep Copy و Shallow Copy

  10. #90

    استفاده از Place Holder ها در کار با رشته ها

    فرض کنیم که :
    int a = 3, b = 5;

    حال میتونیم به جای نوشتن :
    string result = a.ToString() + "+" + b.ToString() + "=" + (a + b).ToString();

    بسادگی بنویسیم :
    string result = string.Format("{0}+{1}={2}", a, b, a + b);


    استفاده از Place Holder ها (حالت دوم) ضمن خوانایی بیشتر برنامه، معمولا کدنویسی کمتری نیز طلب میکند.

  11. #91

    خواندن و نوشتن رنگ یک پیکسل به کمک توابع API

    using System.Drawing;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    [DllImport( "user32.dll" )]
    static extern IntPtr GetDC( IntPtr hWnd );
    [DllImport( "user32.dll" )]
    static extern int ReleaseDC( IntPtr hWnd, IntPtr hDC );
    [DllImport( "gdi32.dll" )]
    static extern int GetPixel( IntPtr hDC, int x, int y );
    [DllImport( "gdi32.dll" )]
    static extern int SetPixel( IntPtr hDC, int x, int y, int color );

    static public Color GetPixel( Control control, int x, int y )
    {
    Color color = Color.Empty;
    if (control != null)
    {
    IntPtr hDC = GetDC( control.Handle );
    int colorRef = GetPixel( hDC, x, y );
    color = Color.FromArgb(
    (int)(colorRef & 0x000000FF),
    (int)(colorRef & 0x0000FF00) >> 8,
    (int)(colorRef & 0x00FF0000) >> 16 );
    ReleaseDC( control.Handle, hDC );
    }
    return color;
    }
    static public void SetPixel( Control control, int x, int y, Color color )
    {
    if (control != null)
    {
    IntPtr hDC = GetDC( control.Handle );
    int argb = color.ToArgb();
    int colorRef =
    (int)((argb & 0x00FF0000) >> 16) |
    (int)(argb & 0x0000FF00) |
    (int)((argb & 0x000000FF) << 16);
    SetPixel( hDC, x, y, colorRef );
    ReleaseDC( control.Handle, hDC );
    }
    }
    منبع : http://www.devtopics.com/c-getpixel-and-setpixel/

  12. #92

    خواندن و نوشتن رنگ یک پیکسل به کمک کلاس Bitmap

    using System.Drawing.Imaging;
    Bitmap bmp = new Bitmap(picturebox1.Image);

    //read
    Color c = bmp.GetPixel(1, 1);

    //write
    bmp.SetPixel(2, 2, c);


    مثال - بنقل از :‌ http://msdn2.microsoft.com/en-us/lib....getpixel.aspx

    private void GetPixel_Example(PaintEventArgs e)
    {

    // Create a Bitmap object from an image file.
    Bitmap myBitmap = new Bitmap("Grapes.jpg");

    // Get the color of a pixel within myBitmap.
    Color pixelColor = myBitmap.GetPixel(50, 50);

    // Fill a rectangle with pixelColor.
    SolidBrush pixelBrush = new SolidBrush(pixelColor);
    e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
    }
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:32 عصر

  13. #93

    انجام عملیات متداول در رجیستری ویندوز

    using Microsoft.Win32;
    // Create SubKey
    Registry.LocalMachine.CreateSubKey(@"Software\Sinp in", RegistryKeyPermissionCheck.ReadWriteSubTree);

    //Create Key and Set Value
    RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"Software\Sinpin ", true);
    reg.SetValue("DWord", "1", RegistryValueKind.DWord);
    reg.SetValue("ExpandString", "1", RegistryValueKind.ExpandString);
    reg.SetValue("QWord", "1", RegistryValueKind.QWord);
    reg.SetValue("String", "1", RegistryValueKind.String);
    reg.SetValue("Unknown", "1", RegistryValueKind.Unknown);

    // Delete Key
    reg.DeleteValue("DWOrd");

    // Delete SubKey
    Registry.LocalMachine.DeleteSubKey(@"Software\Sinp in");

    // Read Key Value
    string val = reg.GetValue("QWord").ToString();

    // Retrieve All Keys
    foreach (string s in reg.GetValueNames())
    MessageBox.Show(s);

  14. #94

    Resize کردن یک تصویر با کدنویسی

    using System.Drawing.Drawing2D;
    private static Image resizeImage(Image imgToResize, Size size)
    {
    int sourceWidth = imgToResize.Width;
    int sourceHeight = imgToResize.Height;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)size.Width / (float)sourceWidth);
    nPercentH = ((float)size.Height / (float)sourceHeight);

    if (nPercentH < nPercentW)
    nPercent = nPercentH;
    else
    nPercent = nPercentW;

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap b = new Bitmap(destWidth, destHeight);
    Graphics g = Graphics.FromImage((Image)b);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

    g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
    g.Dispose();

    return (Image)b;
    }

    منبع : http://blog.paranoidferret.com/?p=11

  15. #95

    Crop کردن یک تصویر (یک برش مستطیلی از تصویر)

    private static Image cropImage(Image img, Rectangle cropArea)
    {
    Bitmap bmpImage = new Bitmap(img);
    Bitmap bmpCrop = bmpImage.Clone(cropArea,
    bmpImage.PixelFormat);
    return (Image)(bmpCrop);
    }

    مثال از نحوه ی استفاده :

    private void button1_Click(object sender, EventArgs e)
    {
    pictureBox2.Image = cropImage(pictureBox1.Image, new Rectangle(10,10,100,100));
    }

    منبع : http://blog.paranoidferret.com/?p=11

  16. #96

    تبدیل یک تصویر رنگی به معادل GrayScal آن

    using System.Drawing.Imaging;
    public static Bitmap MakeGrayscale(Bitmap original)
    {
    //create a blank bitmap the same size as original
    Bitmap newBitmap =
    new Bitmap(original.Width, original.Height);

    //get a graphics object from the new image
    Graphics g = Graphics.FromImage(newBitmap);

    //create the grayscale ColorMatrix
    ColorMatrix colorMatrix = new ColorMatrix(
    new float[][]{
    new float[] {.3f, .3f, .3f, 0, 0},
    new float[] {.59f, .59f, .59f, 0, 0},
    new float[] {.11f, .11f, .11f, 0, 0},
    new float[] {0, 0, 0, 1, 0},
    new float[] {0, 0, 0, 0, 1}});

    //create some image attributes
    ImageAttributes attributes = new ImageAttributes();

    //set the color matrix attribute
    attributes.SetColorMatrix(colorMatrix);

    //draw the original image on the new image
    //using the grayscale color matrix
    g.DrawImage(original,
    new Rectangle(0, 0, original.Width, original.Height),
    0, 0, original.Width, original.Height,
    GraphicsUnit.Pixel, attributes);

    //dispose the Graphics object
    g.Dispose();
    return newBitmap;
    }
    منبع : http://blog.paranoidferret.com/index...-to-greyscale/

    مثال -
    private void button1_Click(object sender, EventArgs e)
    {
    Bitmap b = (Bitmap) pictureBox1.Image;
    pictureBox2.Image = MakeGrayscale(b);
    }

  17. #97

    بدست آوردن مقدار یک Enum از عدد متناظر آن


    public T NumToEnum<T>(int number)
    {
    return (T)Enum.ToObject(typeof(T), number);
    }

    مثال - با فرض داشتن :

    public enum DaysOfWeek
    {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
    }

    میتوانیم بنویسیم :

    int day = 3;

    DaysOfWeek d = NumToEnum<DaysOfWeek>(day);
    //d is now DaysOfWeek.Thursday


    منبع : http://blog.paranoidferret.com/index...from-a-number/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:35 عصر

  18. #98

    بدست آوردن مقدار یک Enum از رشته متنی متناظر با آن


    public static T StringToEnum<T>(string name)
    {
    return (T)Enum.Parse(typeof(T), name);
    }


    مثال - با فرض داشتن :

    public enum DaysOfWeek
    {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
    }

    میتوانیم بنویسیم :

    DaysOfWeek d = StringToEnum<DaysOfWeek>("Monday");
    //d is now DaysOfWeek.Monday if(Enum.IsDefined(typeof(DaysOfWeek), "Katillsday"))
    StringToEnum<DaysOfWeek>("Katillsday");


    منبع : http://blog.paranoidferret.com/index...from-a-string/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:37 عصر

  19. #99

    معرفی یک الگوی ساده از ژنریک سینگلتون


    class GenericSingleton<T> where T : class, new()
    {
    private static T instance;

    public static T GetInstance()
    {
    lock (typeof(T))
    {
    if (instance == null)
    {
    instance = new T();
    }
    return instance;
    }
    }
    }


    مثال از نحوه ی استفاده :
    AutoFactory autoF = GenericSingleton<AutoFactory>.GetInstance();

    منبع : http://blog.paranoidferret.com/index...leton-pattern/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:37 عصر

  20. #100

    چرخاندن یک تصویر با زاویه دلخواه

    private Bitmap rotateImage(Bitmap b, float angle)
    {
    //create a new empty bitmap to hold rotated image
    Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(returnBitmap);
    //move rotation point to center of image
    g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
    //rotate
    g.RotateTransform(angle);
    //move image back
    g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
    //draw passed in image onto graphics object
    g.DrawImage(b, new Point(0, 0));
    return returnBitmap;
    }

    مثال استفاده :
    private void button1_Click(object sender, EventArgs e)
    {
    Bitmap b = (Bitmap) pictureBox1.Image;
    pictureBox2.Image = rotateImage(b, 60);
    }

    منبع : http://blog.paranoidferret.com/index...diting-rotate/

  21. #101

    Lightbulb ارسال تعداد متغیر پارامتر به یک متود

    با استفاده از کلمه کلیدی params مانند نمونه زیر :
     public int Add(params int[] list)
    {
    int sum = 0;
    foreach (int i in list)
    sum += i;
    return sum;
    }



    حال میتونیم این متود را به این شکل صدا بزنیم :

    int ans1 = Add(1);
    int ans2 = Add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    int ans3 = Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    int ans4 = Add();


    نکته :‌ متود میتواند چندین پارامتر دیگر غیر از پارامتر از نوع params بپذیرد اما پارامتر params حتما باید آخرین پارامتر باشد. مانند :
     public void AddAndPrint(string str, params int[] list)
    {
    int sum = 0;
    foreach (int i in list)
    sum += i;
    Console.WriteLine(str + sum);
    }



    منبع : http://blog.paranoidferret.com/index...arams-keyword/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:38 عصر

  22. #102

    Serialize کردن باینری آبجکت در فایل

    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    public void SerializeObject(string filename, Object o)
    {
    Stream stream = File.Open(filename, FileMode.Create);
    BinaryFormatter bFormatter = new BinaryFormatter();
    bFormatter.Serialize(stream, o);
    stream.Close();
    }
    منبع :‌ http://blog.paranoidferret.com/index...cts-to-a-file/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:38 عصر

  23. #103

    Smile ایندکسرها (Indexers)

    ایندکسرها نوعی از پراپرتیها هستند که به شما اجازه میدهند با اشیاء کلاس خود آرایه وار رفتار کنید.
    تعریف یک ایندکسر نیز مانند تعریف یک پراپرتی است و در حالت کلی داریم :
    <Modifier> <Return type> this[arguments]
    {
    get { }
    Set { }
    }
    برای مثال - با فرض داشتن کلاسی مانند :
    class Employee
    {
    private string[] name = new string[10];
    public string this[int index]
    {
    get
    {
    return name[index];
    }
    set
    {
    name[index] = value;
    }
    }
    }
    میتوان نوشت :
    Employee emp = new Employee();
    emp[0] = "Joydip";
    emp[1] = "Manashi";
    emp[2] = "Jini";
    نکته :
    + ایندکسرها حتما باید یک پارامتر داشته باشد.
    + ایندکسرها نمیتوانند استاتیک باشند (بعلت نیاز به this)
    ____________________________________________
    منبع : http://aspalliance.com/800_Properties_and_Indexers_in_C
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:39 عصر

  24. #104
    کاربر دائمی آواتار Masoud_TB
    تاریخ عضویت
    آذر 1386
    محل زندگی
    Tehran
    پست
    165

    Thumbs up Auto Intellisense در web.config

    حتما همه دیدیدن که در Visual Studio 2008 فایل های Configuration رو به صورت Intellisense دار می تونین استفاده کنین. به این معنی که وقتی شما ابتدای کلمه ای رو تایپ می کنین دقیقا مثل کد های سی شارپ خودش ادامش رو براتون نمایش میده :



    نکته ای که وجود داره این است که گاهی اوقات این Intellisense دیگه کار نمی کنه. برای اینکه این مشکل حل بشه خوبه بدونین که دلیل اینه که توی فایل web.config تون در قسمت یه تکه کد اضافه شده که اونو به صورت زیر تغییر داده :

    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

    تنها کاری که باید انجام بدین اینه که برین و namespace مربوطه رو حذف کنین و همان configuration رو داشته باشین:

    <configuration>

    اینجوری مشکلتون حل میشه!

  25. #105
    کاربر دائمی آواتار Masoud_TB
    تاریخ عضویت
    آذر 1386
    محل زندگی
    Tehran
    پست
    165

    Serialize کردن object در XML

    برای Serialize کردن یک object در فایل XML می تونین از این کد استفاده کنین:

    XmlSerializer xmSer = new XmlSerializer(typeof(Person));
    FileStream st = new FileStream("C:\\Test.xml",FileMode.OpenOrCreate);
    Person p = new Person("Ali Rezaei",44);
    xmSer.Serialize(st, p);
    st.Close();
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:40 عصر

  26. #106
    کاربر دائمی آواتار Masoud_TB
    تاریخ عضویت
    آذر 1386
    محل زندگی
    Tehran
    پست
    165

    Exclamation DeSerialize کردن object از XML

    برای بازیابی شیء تون از یک فایل XML می تونین از این کد استفاده کنین:

    XmlSerializer xmSer = new XmlSerializer(typeof(Person));
    FileStream st = new FileStream("C:\\Test.xml",FileMode.Open);
    Person p = xmSer.Deserialize(st) as Person;
    st.Close();
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:40 عصر

  27. #107
    کاربر دائمی آواتار Masoud_TB
    تاریخ عضویت
    آذر 1386
    محل زندگی
    Tehran
    پست
    165

    Lightbulb Serialize کردن object در SOAP XML

    برای Serialize کردن object تون توی فایل Soap می تونین از این کد استفاده کنین.
    دقت کنین که باید System.Runtime.Serialization.Formatters.Soap رو Add Reference و using کنین.


    SoapFormatter soap = new SoapFormatter();
    FileStream st = new FileStream("C:\\Test.soap",FileMode.OpenOrCreate);
    Person p = new Person("Ali Rezaei", 33);
    soap.Serialize(st, p);
    st.Close();
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:40 عصر

  28. #108
    کاربر دائمی آواتار Masoud_TB
    تاریخ عضویت
    آذر 1386
    محل زندگی
    Tehran
    پست
    165

    Exclamation DeSerialize کردن object از SOAP XML

    برای بازیابی شیء تون از یک فایل SOAP می تونین از این کد استفاده کنین:

    SoapFormatter soap = new SoapFormatter();
    FileStream st = new FileStream("C:\\Test.soap",FileMode.Open);
    Person p = soap.Deserialize(st) as Person;
    st.Close();
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:41 عصر

  29. #109

    تعریف عملگر های سفارشی

    class MyClass
    {
    private int number ;
    public MyClass(int _number)
    {
    this.number = _number;
    }
    public static MyClass operator+ (MyClass c1, MyClass c2)
    {
    return new MyClass(c1.number + c2.number);
    }
    }

    تعریف یک Operator overloading همیشه باید بصورت Static و Public باشد و مقدار برگشتی آن نیز نمیتواند void باشد.

    .

  30. #110

    چگونه یک کلاس را مهر وموم کنیم؟

    کافی است در اعلان کلاس و بعد از Access modifier از کلمه کلیدی sealed استفاده کنیم.

    public sealed class MyClass{}
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:41 عصر

  31. #111

    بدست آوردن شماره سریال پراسسور (CPU Id)

    ابتدا System.Management رو به References پروژه بیفزایید و سپس :
    using System.Management;
    public string GetCPUId()
    {
    string cpuInfo = String.Empty;
    //create an instance of the Managemnet class with the
    //Win32_Processor class
    ManagementClass mgmt = new ManagementClass("Win32_Processor");
    //create a ManagementObjectCollection to loop through
    ManagementObjectCollection objCol = mgmt.GetInstances();
    //start our loop for all processors found
    foreach (ManagementObject obj in objCol)
    {
    if (cpuInfo == String.Empty)
    {
    // only return cpuInfo from first CPU
    cpuInfo = obj.Properties["ProcessorId"].Value.ToString();
    }
    }
    return cpuInfo;
    }
    منبع : http://www.dreamincode.net/forums/in...0&#entry307855

  32. #112

    DeSerialize کردن باینری آبجکت از فایل

    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;

    public object DeSerializeObject(string filename)
    {
    object o;
    Stream stream = File.Open(filename, FileMode.Open);
    BinaryFormatter bFormatter = new BinaryFormatter();
    o =
    (ObjectToSerialize)bFormatter.Deserialize(stream);
    stream.Close();
    return o;
    }
    منبع :‌ http://blog.paranoidferret.com/index...cts-to-a-file/
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:42 عصر

  33. #113

    بدست آوردن نام شرکت سازنده پراسسور (CPU Manufacturer)

    ابتدا System.Management رو به References پروژه بیفزایید و سپس :
    using System.Management;
    public string GetCPUManufacturer()
    {
    string cpuMan = String.Empty;
    //create an instance of the Managemnet class with the
    //Win32_Processor class
    ManagementClass mgmt = new ManagementClass("Win32_Processor");
    //create a ManagementObjectCollection to loop through
    ManagementObjectCollection objCol = mgmt.GetInstances();
    //start our loop for all processors found
    foreach (ManagementObject obj in objCol)
    {
    if (cpuMan == String.Empty)
    {
    // only return manufacturer from first CPU
    cpuMan = obj.Properties["Manufacturer"].Value.ToString();
    }
    }
    return cpuMan;
    }
    منبع : http://www.dreamincode.net/forums/in...0&#entry307855

  34. #114

    بدست آوردن میزان فضای خالی یک درایو (پارتیشن)

    ابتدا System.Management رو به References پروژه بیفزایید و سپس :
    using System.Management;

    public double GetHDDFreeSpace(string drive)
    {
    //check to see if the user provided a drive letter
    //if not default it to "C"
    if (drive == "" || drive == null)
    {
    drive = "C";
    }
    //create our ManagementObject, passing it the drive letter to the
    //DevideID using WQL
    ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
    //bind our management object
    disk.Get();
    //return the free space amount
    return Convert.ToDouble(disk["FreeSpace"]);
    }

    منبع : http://www.dreamincode.net/forums/in...0&#entry307855

  35. #115

    بدست آوردن حجم کلی یک درایو (پارتیشن)

    ابتدا System.Management رو به References پروژه بیفزایید و سپس :
    using System.Management;

    public double getHDDSize(string drive)
    {
    //check to see if the user provided a drive letter
    //if not default it to "C"
    if (drive == "" || drive == null)
    {
    drive = "C";
    }
    //create our ManagementObject, passing it the drive letter to the
    //DevideID using WQL
    ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
    //bind our management object
    disk.Get();
    //return the HDD's initial size
    return Convert.ToDouble(disk["Size"]);
    }

    منبع : http://www.dreamincode.net/forums/in...0&#entry307855

  36. #116

    Lightbulb چرا و کی باید از کلاس StringBuilder به جای string استفاده کنیم ؟

    آبجکتهای string در دات نت immutable (غیرقابل تغییر) هستند :‌به این معنا که پس از مقدار گرفتن، دیگر قابل تغییر نیستند.

    به مثال زیر دقت کنید :
    string temp = "a";
    temp = temp + "b";
    temp += "c";
    temp += "d";
    در این مثال ابتدا یک آبجکت از نوع string میسازید، اما در خطوط بعدی با هر بار تغییر مقدار آن؛ آبجکتهای قدیمی فراموش و یک آبجکت جدید از نوع string - با مقدار جدید - ساخته میشود.
    به این ترتیب میشه انتظار داشت که کد زیر چه سربار وحشتناکی روی منابع سیستم میتونه داشته باشه :
    string s2 = new String('x', Int32.Parse(args[0]));
    int loops = Int32.Parse(args[1]);

    for (int j = 0; j < 10000000; j++) {
    string s = "";
    for (int i = loops; i > 0; --i)
    s += s2;
    }
    بصورت کلی در حالتیکه اعمال تغییرات زیاد روی رشته ها نیاز باشد بهتر است آبجکتی از کلاس StringBuilder ساخته و با خاصیت Append آن کار کنیم.

    مثال - پیاده سازی همان کد قبلی :
    string s2 = new String('x', Int32.Parse(args[0]));
    int loops = Int32.Parse(args[1]);

    for (int j = 0; j < 10000000; j++) {
    StringBuilder sb = new StringBuilder();
    for (int i = loops; i > 0; --i)
    sb.Append(s2);
    sb.ToString();
    }
    منبع : http://www.heikniemi.net/hc/archives/000124.html

  37. #117

    ساختن یک لیست ژنریک از اشیاء

    با فرض داشتن کلاسی مانند :
    public class Person
    {
    public Person() { }
    public Person(string _firstName, string _lastName)
    {
    this.firstName = _firstName;
    this.lastName = _lastName;
    }
    private string firstName;
    public string FirstName
    {
    get { return firstName; }
    set { firstName = value; }
    }
    private string lastName;
    public string LastName
    {
    get { return lastName; }
    set { lastName = value; }
    }
    }

    میتونیم بنویسیم :
    List<Person> persons = new List<Person>();
    persons.Add(new Person("ali", "ahmadi");
    persons.Add(new Person("maryam", "hosseini");

  38. #118

    ساختن لیستی از کنترلها در زمان اجرا

    مثال:ساختن 10 دکمه درون یک لیست ژنریک و اختصاص آن به لیست کنترلهای یک فرم
    private void Form1_Load(object sender, EventArgs e)
    {
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < 10; i++)
    {
    Button btn = new Button();
    btn.Size = new Size(120, 22);
    btn.Text = string.Format("Button{0}", i);
    btn.Location = new Point(10, i * 25 + 10);
    buttons.Add(btn);
    }
    this.Controls.AddRange(buttons.ToArray());
    }

  39. #119

    اختصاص دادن رویداد به کنترلهای ساخته شده در runtime

    private void Form1_Load(object sender, EventArgs e)
    {
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < 10; i++)
    {
    Button btn = new Button();
    btn.Size = new Size(120, 22);
    btn.Text = string.Format("Button{0}", i);
    btn.Location = new Point(10, i * 25 + 10);
    btn.Click += new EventHandler(btn_Click);
    buttons.Add(btn);
    }
    this.Controls.AddRange(buttons.ToArray());
    }

    void btn_Click(object sender, EventArgs e)
    {
    for (int i = 0 ; i < 10 ; i++)
    {
    Button btn = sender as Button;
    btn.Location = new Point(btn.Left + i, btn.Top);
    Application.DoEvents();
    }
    }

  40. #120

    sort کردن آبجکتهای یک کلاس با پیاده سازی اینترفیس IComparable

    کلاس مورد نظر باید اینترفیس IComparable رو پیاده سازی کند. (این اینترفیس تنها یک متود CompareTo دارد)
    به نحوه ی پیاده سازی متود CompareTo دقت کنید :
    public class Person : IComparable
    {
    private string _firstname;
    public string Firstname
    {
    get { return _firstname; }
    set { _firstname = value; }
    }

    private string _lastname;
    public string Lastname
    {
    get { return _lastname; }
    set { _lastname = value; }
    }

    private int _age;
    public int Age
    {
    get { return _age; }
    set { _age = value; }
    }

    public Person(string firstname, string lastname, int age)
    {
    _firstname = firstname;
    _lastname = lastname;
    _age = age;
    }

    public int CompareTo(object obj)
    {
    if (obj is Person)
    {
    Person p2 = (Person)obj;
    return _firstname.CompareTo(p2.Firstname);
    }
    else
    throw new ArgumentException("Object is not a Person.");
    }


    public override string ToString()
    {
    return String.Format("{0} {1}, Age = {2}", _firstname,
    _lastname, _age.ToString());
    }
    }
    مثال - Sort کردن افراد از روی اسم کوچک (استفاده از کلاس بالا) :
    List<Person> persons = new List<Person>();
    persons.Add(new Person("Behrouz", "Rad", 30));
    persons.Add(new Person("Omid", "Mottaghi Rad", 31));
    persons.Add(new Person("Mehdi", "Keramati", 32));
    persons.Add(new Person("Ali", "Keshavarz", 33));
    persons.Add(new Person("Mohammad", "Heshemian", 34));
    persons.Add(new Person("Farhad", "XXX", 35));

    //Before Sorting
    listBox1.Items.AddRange(persons.ToArray());

    //ُSorting List
    persons.Sort();

    //Sorted List
    listBox2.Items.AddRange(persons.ToArray());
    منبع : http://codebetter.com/blogs/david.ha...ges/56094.aspx
    آخرین ویرایش به وسیله Mahmoud.Afrad : چهارشنبه 17 تیر 1394 در 12:43 عصر

صفحه 3 از 14 اولاول 1234513 ... آخرآخر

برچسب های این تاپیک

قوانین ایجاد تاپیک در تالار

  • شما نمی توانید تاپیک جدید ایجاد کنید
  • شما نمی توانید به تاپیک ها پاسخ دهید
  • شما نمی توانید ضمیمه ارسال کنید
  • شما نمی توانید پاسخ هایتان را ویرایش کنید
  •