Programming

Tips & Ticks by SAJJAD

Follow me on TwitterRSS Feeds

  • Home
  • Language
    • AS
    • ASM
    • ASP
    • C
    • C#
    • C++
    • CFM
    • CSS
    • Delphi
    • HTML
    • Java
    • JS
    • PHP
    • SQL
      • MS SQL
      • My SQL
      • T-SQL
    • VB
    • Verilog
    • VHDL
    • WHS
    • XML
  • News
  • Technology
    • LinQ

C# Sarray (Advaned Generic/Object Array)

Apr 12th

Posted by SAJJAD in C#

1 comment

Sarray: Queueable, Stackable, Enumerable, Collectable, Listable, Disposable, Timmeable Array !
Add, Insert, Remove, Enqueue, Dequeue, Pop, Push @ Range

Enjoy, SAJJAD

    [System.Diagnostics.DebuggerDisplay("Count = { Count }")]
    public class Sarray< T > : ISarray, ISarray< T >
    {
        protected T[] Items;

        public Sarray(bool queueTimered, double timmerTick, int queuesCapacity)
        {
            this.Clear();

            if (queueTimered)
            {
                this.queueTimer = new Timer(timmerTick);
                this.queueTimer.Elapsed += new ElapsedEventHandler(queueTimer_Elapsed);
            }

            this.queuesCapacity = queuesCapacity;

            this.Enqueues();
            this.Dequeues();

            if (queueTimered)
            {
                this.queueTimer.Start();
            }
        }

        #region { List }

        int IList.Add(object value)
        {
            return this.InsertCore(this.Items.Length, (T)value);
        }

        void IList.Clear()
        {
            this.Clear();
        }

        bool IList.Contains(object value)
        {
            return this.Contains((T)value);
        }

        int IList.IndexOf(object value)
        {
            return this.IndexOf((T)value);
        }

        void IList.Insert(int index, object value)
        {
            this.InsertCore(index, (T)value);
        }

        bool IList.IsFixedSize
        {
            get { return false; }
        }

        bool IList.IsReadOnly
        {
            get { return false; }
        }

        void IList.Remove(object value)
        {
            this.DeleteCore((T)value);
        }

        void IList.RemoveAt(int index)
        {
            this.DeleteCore(index, index + 1);
        }

        object IList.this[int index]
        {
            get
            {
                return this[index];
            }
            set
            {
                this[index] = (T)value;
            }
        }

        void ICollection.CopyTo(Array array, int index)
        {
            if (this.IsIndex(index, false))
            {
                Items.CopyTo(array, index);
            }
        }

        int ICollection.Count
        {
            get { return this.Items.Length; }
        }

        bool ICollection.IsSynchronized
        {
            get { return true; }
        }

        object ICollection.SyncRoot
        {
            get { return this; }
        }

        #endregion

        #region { IList< T > }

        public virtual int IndexOf(T item)
        {
            for (int i = 0; i < this.Items.Length; i++)
            {
                if (this.Items[i].Equals(item))
                    return i;
            }

            return -1;
        }

        public virtual void Insert(int index, T item)
        {
            this.InsertCore(index, item);
        }

        public virtual void RemoveAt(int index)
        {
            this.DeleteCore(index, index + 1);
        }

        public virtual T this[int index]
        {
            get
            {
                return this.Seek(index);
            }
            set
            {
                T co = this.Seek(index);
                if (co != null)
                {
                    co = value;
                }
            }
        }

        public virtual void Add(T item)
        {
            this.InsertCore(this.Items.Length, item);
        }

        public virtual void Clear()
        {
            this.Items = new T[] { };
        }

        public virtual bool Contains(T item)
        {
            foreach (T co in this.Items)
            {
                if (co.Equals(item))
                    return true;
            }
            return false;
        }

        public virtual void CopyTo(T[] array, int arrayIndex)
        {
            if (this.IsIndex(arrayIndex, false))
            {
                Array.Copy(this.Items, array, arrayIndex);
            }
        }

        public virtual int Count
        {
            get { return this.Items.Length; }
        }

        public virtual bool IsReadOnly
        {
            get { return false; }
        }

        public virtual bool Remove(T item)
        {
            return this.RemoveRange(item) > 0;
        }

        public virtual IEnumerator< T > GetEnumerator()
        {
            foreach (T co in this.Items)
                yield return co;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.Items.GetEnumerator();
        }

        #endregion

        #region { IDisposible }

        private bool disposed = false;
        public bool Disposed
        {
            get
            {
                return this.disposed;
            }
        }

        public virtual void Dispose()
        {
            if (!this.disposed)
            {
                this.Items = null;
                this.enqueue = null;
                this.dequeue = null;

                this.queueTimer.Dispose();
                this.queueTimer = null;
            }
        }

        #endregion

        public virtual bool IsIndex(int index, bool withEnd)
        {
            if (withEnd)
                return index >= 0 && index <= this.Items.Length;

            return index >= 0 && index < this.Items.Length;
        }

        public virtual T Seek(int index)
        {
            for (int i = 0; i < this.Items.Length; i++)
            {
                if (i == index)
                    return this.Items[i];
            }

            return default(T);
        }
        public virtual IEnumerable Seek(int from, int to)
        {
            if (this.IsIndex(from, false) && this.IsIndex(to, true) && from < to && from != to)
            {
                for (int i = 0; i < this.Items.Length; i++)
                {
                    if (i >= from && i < to)
                    {
                        yield return this.Items[i];
                    }
                }
            }
        }

        public virtual int Push(T iteme)
        {
            return this.InsertCore(this.Items.Length, iteme);
        }
        public virtual int PushRange(params T[] itemes)
        {
            return this.InsertCore(this.Items.Length, itemes);
        }
        public virtual int AddRange(params T[] items)
        {
            return this.InsertCore(this.Items.Length, items);
        }
        public virtual int InsertRange(int index, params T[] items)
        {
            return this.InsertCore(index, items);
        }

        public virtual int Pop(int count = 1)
        {
            if (count > 0)
                return this.DeleteCore(this.Items.Length - count, this.Items.Length);

            return 0;
        }
        public virtual int RemoveRange(params T[] items)
        {
            return this.DeleteCore(items);
        }

        protected virtual int InsertCore(int index, params T[] items)
        {
            Int32 newRealMembers = 0;

            if (items != null && this.IsIndex(index, true))
            {
                if (items.Length > 0) // At least one new child want added
                {
                    // We thing all new childs are new
                    T[] newMembers = new T[items.Length];

                    // Flag for child existance
                    Boolean exist = false;

                    // Check existance
                    foreach (T item in items)
                    {
                        if (item != null)
                        {
                            exist = false;
                            foreach (T at in this.Items)
                                if (at.Equals(item))
                                    exist = true;

                            if (!exist)
                                newMembers[newRealMembers++] = item;
                        }
                    }

                    if (newRealMembers > 0)
                    {
                        T[] newArray = new T[this.Items.Length + newRealMembers];

                        for (int i = 0, j = 0; i < newArray.Length; )
                        {
                            if (index == i)
                            {
                                for (int z = 0; z < newRealMembers; z++)
                                {
                                    newArray[i++] = newMembers[z];
                                }
                            }
                            else
                            {
                                newArray[i++] = this.Items[j++];
                            }
                        }
                        this.Items = newArray;
                    }
                }
            }

            return newRealMembers;
        }
        protected virtual int DeleteCore(params T[] items)
        {
            Int32 newMembers = 0, lastSize = 0;

            if (items != null)
            {
                if (items.Length > 0)
                {
                    T[] newArray = new T[this.Items.Length];

                    // Is item exist ?
                    Boolean exist = false;

                    // Find no selected childs
                    foreach (T t in this.Items)
                    {
                        exist = false;

                        foreach (T item in items)
                        {
                            if (t.Equals(item))
                            {
                                exist = true;
                                break;
                            }
                        }

                        if (!exist)
                        {
                            newArray[newMembers++] = t;
                        }
                    }

                    if (newMembers > 0 && newMembers != this.Items.Length)
                    {
                        lastSize = this.Items.Length;
                        Array.Resize(ref newArray, newMembers);
                        this.Items = newArray;
                    }
                }
            }

            return lastSize - newMembers;
        }
        protected virtual int DeleteCore(int from, int to)
        {
            int applied = 0;

            if (this.IsIndex(from, false) && this.IsIndex(to, true) && from < to && from != to)
            {
                T[] newArray = new T[this.Items.Length - (from - to)];

                for (int i = 0, newIndex = 0; i < this.Items.Length; i++)
                {
                    if (i >= from && i < to)
                    {
                        newArray[newIndex++] = this.Items[i];
                    }
                }
                applied = from - to;
                this.Items = newArray;

            }

            return applied;
        }

        #region { Timer }

        private bool queueTimered = false;
        public bool QueueTimered
        {
            get
            {
                return this.queueTimered;
            }
        }

        private Timer queueTimer;
        private void queueTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Enqueues();
            this.Dequeues();
        }

        ///

        /// Queue Refresh Time (100 to 10000 ms, 1000 is default)
        /// 

        public double QueueTick
        {
            get
            {
                return this.queueTimer.Interval;
            }
            set
            {
                if (value > 100 && value < 10000 && this.queueTimered)
                {
                    this.queueTimer.Interval = value;
                }
            }
        }

        #endregion

        protected int queuesCapacity = 0;
        public int QueuesCapacity
        {
            get
            {
                return this.queuesCapacity;
            }
            set
            {
                if (value >= 0 && value <= 10000)
                {
                    this.queuesCapacity = value;
                }
            }
        }

        #region { Enqueue }

        protected T[] enqueue;

        protected int enqueueCount = 0;
        public int EnqueueCount
        {
            get
            {
                return this.enqueueCount;
            }
        }

        public virtual int Enqueue(params T[] items)
        {
            if (items != null)
            {
                if (items.Length > 0)
                {
                    if (this.enqueue.Length > enqueueCount + items.Length)
                    {
                        int added = 0, nulled = 0;
                        for (int i = 0; i < this.enqueue.Length; i++)
                        {
                            if (this.enqueue[i] == null)
                            {
                                foreach (T co in items)
                                {
                                    if (co == null)
                                    {
                                        nulled++;
                                    }
                                    else
                                    {
                                        this.enqueue[i] = co;
                                        added++;
                                        this.enqueueCount++;
                                        break;
                                    }
                                }

                                // All object checked
                                if (added + nulled == items.Length)
                                {
                                    break;
                                }
                            }
                        }

                        return added;
                    }
                    else
                    {
                        this.Enqueues();
                        return this.InsertCore(this.Items.Length, items);
                    }
                }
            }

            return 0;
        }

        public void Enqueues()
        {
            if (this.enqueue == null)
            {
                this.enqueue = new T[this.queuesCapacity];
            }

            if (this.enqueueCount > 0)
            {
                this.InsertCore(this.Items.Length, this.enqueue);
                this.enqueueCount = 0;
            }
        }

        #endregion

        #region { Dequeue }

        protected T[] dequeue;

        protected int dequeueCount = 0;
        public int DequeueCount
        {
            get
            {
                return this.dequeueCount;
            }
        }

        public virtual int Dequeue(params T[] items)
        {
            if (items != null)
            {
                if (items.Length > 0)
                {
                    if (this.dequeue.Length < dequeueCount + items.Length)
                    {
                        int added = 0, nulled = 0;
                        for (int i = 0; i < this.dequeue.Length; i++)
                        {
                            if (this.dequeue[i] == null)
                            {
                                foreach (T co in items)
                                {
                                    if (co == null)
                                    {
                                        nulled++;
                                    }
                                    else
                                    {
                                        this.dequeue[i] = co;
                                        added++;
                                        dequeueCount++;
                                        break;
                                    }
                                }

                                // All object checked
                                if (added + nulled == items.Length)
                                {
                                    break;
                                }
                            }
                        }

                        return added;
                    }
                    else
                    {
                        this.Dequeues();
                        return this.DeleteCore(items);
                    }
                }
            }

            return 0;
        }

        public void Dequeues()
        {
            if (this.dequeue == null)
            {
                this.dequeue = new T[this.queuesCapacity];
            }

            if (this.dequeueCount > 0)
            {
                this.DeleteCore(this.dequeue);
                this.dequeueCount = 0;
            }
        }

        #endregion
    }
Array, Collectable, Dequeue, Disposable, Enqueue, Enumerable, Generic, IDisposable, Listable, Object, Queueable, Sarray, Stackable

C# Define Field, Property, Method or Class

Oct 30th

Posted by SAJJAD in C#

No comments

[|new] [public|internal|protected|private] [static] [|virtual|abstract|sealed] [|override] Type NAME;
Class, Field, Method, Property

C# partial Keyword

Oct 25th

Posted by SAJJAD in C#

No comments

using System;

namespace ConsoleApplication
{
	static class Program
	{
		static void Main()
		{
			User a = new User();
			Console.WriteLine(User.Instance);

			User b = new User();
			Console.WriteLine(User.Instance);

			Console.Read();
		}
	}

	public enum Gender
	{
		Male,
		Female
	}

	public partial class User
	{
		private Gender _gender;

		public Gender Gender
		{
			get
			{
				return this._gender;
			}

			set
			{
				this._gender = value;
			}
		}

		public User()
		{
			Instance++;
		}

		~User()
		{
			Instance--;
		}
	}

	public partial class User
	{
		public static int Instance = 0;
		public static readonly User Empty;
	}
}
Keyword, partial

C# virtual Keywords: More speed

Oct 14th

Posted by SAJJAD in C#

No comments

using System;

namespace ConsoleApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Area of 5 is: " + (new Circle(5).Area()).ToString());
			Console.WriteLine("Perimeter of 5 is: " + (new Circle(5).Perimeter()).ToString());

			Circle C = new Circle(8.5);
			Console.WriteLine("\nArea of 8.5 is: " + C.Area().ToString());
			Console.WriteLine("Perimeter of 8.5 is: " + C.Perimeter().ToString());

			Console.Read();
		}
	}

	abstract class Shape
	{
		public double X, Y;

		public Shape() : this(0) { }
		public Shape(double X)
		{
			this.X = this.Y = X;
		}
		public Shape(double X, double Y)
		{
			this.X = X;
			this.Y = Y;
		}

		public virtual double Area()
		{
			return this.X * this.Y;
		}

		public virtual double Perimeter()
		{
			return 2 * this.X * this.Y;
		}
	}

	sealed class Circle : Shape
	{
		public Circle() : base(0) { }
		public Circle(double Radius) : base(Radius) { }

		public override double Area()
		{
			return Math.PI * this.X * this.X;
		}

		public override double Perimeter()
		{
			return 2 * Math.PI * this.X;
		}
	}
}
Keywords, virtual

C# params Keywords

Oct 14th

Posted by SAJJAD in C#

No comments

using System;

namespace ConsoleApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			if (Containt(typeof(int), new object[] { true, 1, 110.1F, 20L, 80.0001D, "SAJJAD", DateTime.Now }))
			{
				Console.WriteLine("Array contain Int32 type !");
			}

			if (Containt(typeof(DateTime), true, 1, 110.1F, 20L, 80.0001D, "SAJJAD", DateTime.Now))
			{
				Console.WriteLine("Array contain Datetime type !");
			}

			Console.ReadLine();
		}

		static bool Containt(Type type, params object[] list)
		{
			foreach (object obj in list)
				if (obj.GetType() == type)
					return true;

			return false;
		}
	}
}
Keywords, params

Abstract, Sealed & Static modifiers in C#

Oct 10th

Posted by SAJJAD in C#

1 comment

C# provides many modifiers for use with types and type members. Of these, three can be used with classes: abstract, sealed and static.

abstract
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class

abstract class A {}
A a = new A(); //Error

sealed
When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.

sealed class A {}
class B:A {} //Error

static
The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created

static class A {}
A a = new A(); //Error
/* All member must be static */
abstract, Guidline, Modifiers, sealed, Static

C# Reserved and Contextual Keywords

Oct 8th

Posted by SAJJAD in C#

1 comment

Specification keywords
abstract | as | base | bool | break | byte | case | catch | char | checked | class | const | continue | decimal | default | delegate | do | double | else | enum | event | explicit | extern | false | finally | fixed | float | for | foreach | goto | if | implicit | in | int | interface | internal | is | lock | long | namespace | new | null | object | operator | out | override | params | private | protected | public | readonly | ref | return | sbyte | sealed | short | sizeof | stackalloc | static | string | struct | switch | this | throw | true | try | typeof | uint | ulong | unchecked | unsafe | ushort | using | virtual | void | volatile | while

Magic keywords
__arglist | __makeref | __reftype | __refvalue

Keywords as an identifier
@typeof @goto = @for.@switch(@throw);

Preprocessor keywords
#define | hidden | default | disable | restore | checksum

C# 1.0 Contextual keywords
get | set | value | add | remove

C# 2.0 Contextual keywords
where | partial | global | yield | alias

C# 3.0 Contextual keywords
from | join | on | equals | into | orderby | ascending | descending | group | by | select | let | var

C# 4.0 Contextual keywords
dynamic

Contextual, Keywords, Reserved, Specification

C# speed: ‘return’ vs ‘yield return’

Oct 7th

Posted by SAJJAD in C#

No comments

Declare;

public static T[] Reserve< T>(T[] array)
{
	T[] newArray = new T[array.Length];

	for (i = 0; i < array.Length; i++)
		newArray[i] = array[array.Length - 1 - i];

	return newArray;
}

public static IEnumerable ReserveAsync< T>(T[] array)
{
	for (i = 0; i < array.Length; i++)
		yield return array[array.Length - 1 - i];
}

Use;

int[] ii = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

long a;

a = DateTime.Now.Ticks;
foreach (int i in xArray.Reserve(ii))
	Debug.WriteLine(i);
Debug.WriteLine(DateTime.Now.Ticks - a);

a = DateTime.Now.Ticks;
foreach (int i in xArray.ReserveAsync(ii))
	 Debug.WriteLine(i);
Debug.WriteLine(DateTime.Now.Ticks - a);

Result;
ReserveAsync often is 60% faster than Reserve

Array, IEnumerable, return, Speed, T, yield

Dynamic in C# 4.0: Introducing the ExpandoObject

Oct 5th

Posted by SAJJAD in C#

No comments

XElement contactXML =
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Phone", "206-555-0144"),
        new XElement("Address",
            new XElement("Street1", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    );
dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
contact.Address = new ExpandoObject();
contact.Address.Street = "123 Main St";
contact.Address.City = "Mercer Island";
contact.Address.State = "WA";
contact.Address.Postal = "68402";
dynamic contacts = new List();

contacts.Add(new ExpandoObject());
contacts[0].Name = "Patrick Hines";
contacts[0].Phone = "206-555-0144";

contacts.Add(new ExpandoObject());
contacts[1].Name = "Ellen Adams";
contacts[1].Phone = "206-555-0155";

For more details going here.

C# 4.0, Dynamic, ExpandoObject

Fastest Coping Array in .Net

Oct 5th

Posted by SAJJAD in C#

No comments

[MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable);
Array, Coping, Copy
12»
  • Recent Posts

    • C# Sarray (Advaned Generic/Object Array)
    • C# Define Field, Property, Method or Class
    • C# partial Keyword
    • C# virtual Keywords: More speed
    • C# params Keywords
    • Abstract, Sealed & Static modifiers in C#
    • C# Reserved and Contextual Keywords
    • C# speed: ‘return’ vs ‘yield return’
    • Dynamic in C# 4.0: Introducing the ExpandoObject
    • Fastest Coping Array in .Net
  • Recent Comments

    • JIM on C# Reserved and Contextual Keywords
    • Medical Billing on C# Sarray (Advaned Generic/Object Array)
    • grants for women on Abstract, Sealed & Static modifiers in C#
    • برنامه‌نویسی « Windows 7 | ویندوز 7 on Start, Introduction
    • سجاد on Start, Introduction
  • RSS Windows 7

    • Expired
      سلام ادامه سرنوشت سایت ویندوز 7 را در اینجا بخوانید یاعلی […]
    • دانلود نسخه (بتا 4) نرم‌افزار Firefox ویرایش 3.6
      سلام آخرین نسخه نرم‌افزار فایرفاکس منتشر شد. نسخه ارائه شده از خانواده ویرایش 3.6 می‌باشد که در مرحله بتا 4 قرار گرفته است. این نسخه حاوی 134 رفع خطا نسبت به نسخه بتا 3 خود است. صفحه خانگی نرم‌افزار دانلود نسخه 3.6 بتا 4 انگلیسی | دانلود نسخه 3.6 بتا 4 فارسی یاعلی […]
    • سیستم عامل گوگل «کرومیوم» معرفی شد /آنچه درباره سیستم عامل گوگل باید بدانیم
      سلام اولین نسخه سیستم عامل گوگل با نام «کرومیوم» منتشر شد. این سیستم عامل ظاهرا قرار است پوشش دهنده بخشی از فعالیت‌های گوگل در اینترنت باشد. تاریخچه؛ چند ماه پیش تصاویری منتشر شد (در آرشیو سایت موجود است) که نشان دهنده فعالیت گوگل بر روی یک سیستم عامل بود. تصاویر حاوی محرمانه بودن این سیستم […]
    • دانلود نسخه (بتا 2) نرم‌افزار 2010 Office ویرایش 14.4514.1007
      سلام آخرین نسخه نرم‌افزار محبوب مایکروسافت آفیس 2010 رسما منتشر شد. این نسخه دومین نسخه آزمایشی این نرم‌افزار می‌باشد که برای اولین بار به طور رسمی برای دانلود در سایت مایکروسافت قرار گرفته است. این نرم‌افزار همانند ویندوز 7 ارائه می‌شود به طوریکه کاربر بایستی عضو سایت Live.com باشد و مطابق با شناسه کاربری وی […]
    • برجسته‌ترین تغییرات 13 اکتبر 2009 در ویندوز 7
      سلام همزمان با انتشار به‌روزرسانی 13 اکتبر 2009 برای ویندوز 7 حدود 50 فایل شامل تغییراتی شده اند. این تغییرات پیش‌تر در اینجا اطلاع‌رسانی و در اینجا جهت دانلود منتشر شده بود. مهمترین تغییرات؛ نرم‌افزار Windows Explorer به نسخه 6.1.7600.16404 ارتقا یافته است. نرم‌افزار Windows Media Player به نسخه 12.0.7600.16415 ارتقا یافته است. فایل Ehshell.dll […]
Mystique theme by digitalnature | Powered by WordPress
RSS Feeds XHTML 1.1 Top