Powershell’s tricks

Suppose you have a deep and complex folder tree and you need a list of folders containing specific files –like CSS files; say you wanna minify them; what would you do?

a clean dir *.css /s /b returns the files’ bare name and path, but there’s no grouping there… Oh wait! we have powershell! Let’s use it!

ls -Filter *.css -Recurse -Name | group -Property directoryname

^^ this returns a Dictionary> where the key is the unified folder names where .css files reside. easy huh? OK now go and minify those files… DONE? Oh wait! what if you’ve missed some files? I won’t check back manually! I can’t actually act like a ASP:Repeater! here comes the Powershell again!

$list=ls -Filter *.css -Recurse -Exclude *.min.css -Name
$minlist=ls -Filter *.min.css -Recurse -Name
$list | where {$minlist -cnotcontains $_.Replace(".css", ".min.css")}

and yes! there was a file I missed!

Minified the file and now I’m good to go!

Bulk Backup All SQL databases

This is a simple SQL-T script to backup every database you have on an SQL-Server Engine.


USE master;
GO
DECLARE @dbName NVARCHAR(MAX);
DECLARE curDBs CURSOR FAST_FORWARD READ_ONLY FOR SELECT [s].[name] FROM [sys].[sysdatabases] AS s WHERE [s].[dbid] > 4;
OPEN curDBs
FETCH NEXT FROM curDBs INTO @dbName
WHILE @@FETCH_STATUS = 0
BEGIN
	DECLARE @cmd NVARCHAR(MAX);
	SET @cmd = N'BACKUP DATABASE ['+ @dbName +'] TO DISK = N''D:\xData\_backups\'+ @dbName +'.bak'' WITH NOFORMAT, NOINIT, NAME = ''' + @dbName + N'-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10';
	PRINT @cmd;
	EXEC [sys].[sp_executesql] @cmd;

	FETCH NEXT FROM curDBs INTO @dbName
END
CLOSE curDBs
DEALLOCATE curDBs

MS-DOS Counted Loops – ITERATION

Using the /L switch for the FOR command, it is possible to count through a loop in MS-DOS; just like any other scripting languages.

Consider this as a very simple sample. It counts from 0 to 99; including both 0 and 99; with a step size of 1 and executes the loop’s body for each iteration.

FOR /L %i IN (0,1,99) DO (
  echo Attempt# %i
  nslookup google.com 4.2.2.4
)

RAR CLI to split files

The popular winRAR has a CLI that comes really handy specifically when you need a superior compression while developing application. The good news is you can fire a process to run the RAR.EXE; but the downside is there’s no obvious help for the CLI except the minimally provided help on the command prompt.

The following command should be a rather complete help for some frequently-used features of RAR.EXE:

rar a -r -v100m -m5 -hpPassword D:TempRARTeststest1.rar "iPhone 2012-10-18*.*"

Description:

a		Means "add to archive".<br />
r		Means do the "addition" recursively for sub-folders.<br />
-v100m		Means the archive should be splitted into 100m sub-archives.
		m: 1024 bytes MEGA = 1024*1024 bytes
		M: 1000 bytes MEGA = 1000*1000 bytes
		There are also k and K suffixes for KILO<br />
-m5		Tells the RAR.EXE to use its maximum compression.
		the number after "-m" can be an integer in the range of [0,5]
		0: No compression = store
		3: Normal compression
		5: Maximum compression
-hpPassword	Uses the phrase "Password" to encrypt the archive's contentand also
		encrypts the archive's headers containing the names of files/folders in the archive.
		if "-p" is used instead of "-hp", the contents will be encrypted only.
		NOTE: -p leaves the filenames to be openly seen...

D:TempRARTeststest1.rar
is the path to target archive to be created and

“iPhone 2012-10-18*.*”
is the source file(s)/folder(s) path to be compressed into the archive.
Note that if  RAR.EXE will include the folder structure of your source files/folders into the archive. In our example, the archive will contain a folder called “iPhone 2012-10-18″ and its files and sub-folders. The source name is quoted because it contains spaces.

Deep Object Copy

یه وقتهایی لازم میشه که ۲ تا Instance از ۲ تا کلاس مختلف که Property های شبیه به هم دارن رو به صورت یک طرفه Sync کنیم. در واقع میخوایم یکیشون رو توی اون یکی کپی کنیم.

برای بهتر روشن شدن موضوع یه مثال میزنم. فرض کنید که 4 تا کلاس داریم به این صورت:

Tester.DeepCopy.Models.Province
Tester.DeepCopy.Models.City
Tester.DeepCopy.ClumsyModels.ClumsyProvince
Tester.DeepCopy.ClumsyModels.ClumsyCity

کد داخل این کلاسها رو میتونین تصور کنین که چی خواهد بود:

Tester.DeepCopy.Models:

using System.Text;

namespace Tester.DeepCopy.Models {
	public class City {
		public long Id { get; set; }
		public long ProvinceId { get; set; }
		public string Title { get; set; }

		public Province Province { get; set; }

		public override string ToString() {
			StringBuilder sb = new StringBuilder();
			sb.Append(&amp;amp;quot;{&amp;amp;quot;);
			System.ComponentModel.PropertyDescriptorCollection pdcSource = 
				System.ComponentModel.TypeDescriptor.GetProperties(this.GetType());
			for (int i = 0; i < pdcSource.Count; i++) {
				System.ComponentModel.PropertyDescriptor pd = pdcSource[i];
				sb.AppendFormat(&amp;amp;quot;{0}={1}&amp;amp;quot;, pd.Name, pd.GetValue(this));
				if (i < pdcSource.Count - 1) sb.Append(&amp;amp;quot;, &amp;amp;quot;);
			}
			sb.Append(&amp;amp;quot;}&amp;amp;quot;);
			return sb.ToString();
		}
	}

	public class Province {
		public long Id { get; set; }
		public string Title { get; set; }

		public override string ToString() {
			StringBuilder sb = new StringBuilder();
			sb.Append(&amp;amp;quot;{&amp;amp;quot;);
			System.ComponentModel.PropertyDescriptorCollection pdcSource = 
				System.ComponentModel.TypeDescriptor.GetProperties(this.GetType());
			for (int i = 0; i < pdcSource.Count; i++) {
				System.ComponentModel.PropertyDescriptor pd = pdcSource[i];
				sb.AppendFormat(&amp;amp;quot;{0}={1}&amp;amp;quot;, pd.Name, pd.GetValue(this));
				if (i < pdcSource.Count - 1) sb.Append(&amp;amp;quot;, &amp;amp;quot;);
			}
			sb.Append(&amp;amp;quot;}&amp;amp;quot;);
			return sb.ToString();
		}
	}
}

Tester.DeepCopy.ClumsyModels:

using System.Text;

namespace Tester.DeepCopy.ClumsyModels {
	public class ClumsyCity {
		public string Title { get; set; }
		public long Id { get; set; }
		public ClumsyProvince Province { get; set; }
		public long ProvinceId { get; set; }

		public override string ToString() {
			StringBuilder sb = new StringBuilder();
			sb.Append(&amp;amp;quot;{&amp;amp;quot;);
			System.ComponentModel.PropertyDescriptorCollection pdcSource = 
				System.ComponentModel.TypeDescriptor.GetProperties(this.GetType());
			for (int i = 0; i < pdcSource.Count; i++) {
				System.ComponentModel.PropertyDescriptor pd = pdcSource[i];
				sb.AppendFormat(&amp;amp;quot;{0}={1}&amp;amp;quot;, pd.Name, pd.GetValue(this));
				if (i < pdcSource.Count - 1) sb.Append(&amp;amp;quot;, &amp;amp;quot;);
			}
			sb.Append(&amp;amp;quot;}&amp;amp;quot;);
			return sb.ToString();
		}
	}

	public class ClumsyProvince {
		public long Id { get; set; }
		public string Title { get; set; }

		public override string ToString() {
			StringBuilder sb = new StringBuilder();
			sb.Append(&amp;amp;quot;{&amp;amp;quot;);
			System.ComponentModel.PropertyDescriptorCollection pdcSource = System.ComponentModel.TypeDescriptor.GetProperties(this.GetType());
			for (int i = 0; i < pdcSource.Count; i++) {
				System.ComponentModel.PropertyDescriptor pd = pdcSource[i];
				sb.AppendFormat(&amp;amp;quot;{0}={1}&amp;amp;quot;, pd.Name, pd.GetValue(this));
				if (i < pdcSource.Count - 1) sb.Append(&amp;amp;quot;, &amp;amp;quot;);
			}
			sb.Append(&amp;amp;quot;}&amp;amp;quot;);
			return sb.ToString();
		}
	}
}

همونطور که میبینین، کد داخل کلاسها، شبیه به هم هست، ولی کلاسهای توی ۲ تا Namespace مجزا هستند و ترتیب Property ها یکسان نیست.

حالا موقعیتی رو در نظر بگیرید که یک Instance از کلاس City دارید و میخواین اون رو کپی کنین توی یه Instance از کلاس ClumsyCity. ابتدایی ترین راه اینه که Propertyهاش رو نظیر به نظیر برابر کنین با Property های City؛ ولی اگه تعداد Proprty ها زیاد بود چی؟ اگه فقط همین 2 تا کلاس نبود و مثلاً با 20 تا کلاس باید همین کار رو میکردین چطور!!؟

مثلاً موقعیتی رو در نظر بگیرید که توی یک Solution شما هم برنامه ی Web-Based دارید و  هم پروژه‌ی Smart Device. دیتابیسهای روی Deviceها رو میخواین Sync کنین با سرور اصلی. چه می کنین!!؟

اینجاست که DeepCopy که یه Extension Method خیلی ساده هست به درد میخوره:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;

namespace DNE.ExtensionMethods {
	/// <summary>
	/// My Extension Methods
	/// </summary>
	public static class Extensions {
		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="target"></param>
		/// <param name="source"></param>
		public static void DeepCopy(this Object target, T source) {
			if (source == null) { target = null; return; }
			if (target == null) { throw new ArgumentNullException(&amp;amp;quot;target&amp;amp;quot;); }

			PropertyDescriptorCollection pdcSource = TypeDescriptor.GetProperties(source.GetType());
			PropertyDescriptorCollection pdcTarget = TypeDescriptor.GetProperties(target.GetType());

			pdcSource.Cast().ToList().ForEach(pdS => {
				PropertyDescriptor pdT = pdcTarget.Find(pdS.Name, true);
				if (pdT != null) {
					if (pdT.PropertyType == pdS.PropertyType) {
						pdT.SetValue(target, pdS.GetValue(source));
					} else {
						ConstructorInfo ciCtor = pdT.PropertyType.GetConstructor(Type.EmptyTypes);
						if (pdT.GetValue(target) == null) {
							pdT.SetValue(target, ciCtor.Invoke(null));
							pdT.GetValue(target).DeepCopy(pdS.GetValue(source));
						} else {
							pdT.GetValue(target).DeepCopy(pdS.GetValue(source));
						}
					}
				}
			});
		}
	}
}

طرز استفاده اش هم خیلی ساده است:

static void TestDeepCopy() {
	City c1 = new City {
		Id = 1,
		ProvinceId = 1,
		Title = "Tehran",
		Province = new Province { 
			Id = 1,
			Title = "Tehran"
		}
	};
	ClumsyCity c2 = new ClumsyCity();
	c2.DeepCopy(c1);

	Console.WriteLine("City: {0}", c1);
	Console.WriteLine("Clumsy City: {0}", c2);

}

نتیجه‌ی اجرای متد بالا اینطور میشود:

City: {Id=1, ProvinceId=1, Title=Tehran, Province={Id=1, Title=Tehran}}
Clumsy City: {Title=Tehran, Id=1, Province={Id=1, Title=Tehran}, ProvinceId=1}
Press any key to continue . . .

Execute a command on every file inside current directory

for file in `find -maxdepth 1 -type f`; do echo -n > $file; done

backup yum GPG Keys

In case you’re looking for yum‘s repository GPG Keys, you can find them under /etc/pki/rpm-gpg

Convert Non-Generic IEnumerator to IEnumerable

/// <summary>
/// Converts a Non-Generic IEnumerator to IEnumerable
/// </summary>
/// <param name="enumerator"></param>
/// <returns></returns>
public static IEnumerable ToIEnumerable(this IEnumerator enumerator) {
	while (enumerator.MoveNext()) {
		yield return enumerator.Current;
	}
	yield break;
}

using “netcat” as a port scanner on linux

There are certain time when you need to do a port scan on a remote host in a Linux shell. There are many scripts flying all over the internet giving you this ability; but wait! There’s a native way to do this.

The “netcat” command [perhaps you’ll need to install it using yum or whatever installation method you prefer] can do the job really nice!
nc <host-name-or-ip-address> -z -w 1 <start-port>-<end-port>

example:
nc -z -w 1 192.168.1.1 1-65535
this will scan for ports from 1 to 65536 on 192.168.1.1 and will wait 1 second before throwing a timeout for every port being checked.

Nice trick, wasn’t it?

اعتراض

یعنی اعتراض کردنم بلد نیستیم ها!!
ملت جوگیر پاشدن رفتم روی یه عکس از پادشاه عربستان اعتراض کنن به اسمی که این عربها برای خلیج فارس گذاشتن، یکی در میون فحش خواهر و مادر باید بخونی اون وسط!

بابا! معترضین؟ اوکی! مثل بچه ی آدمیزاد به یارو بگین که بفهمه با مردم با فرهنگی طرفه؛ وقتی میرین اونجا رو به فحش می بندین، اولاً طرف می فهمه که دردتون اومده، حالا هی میخواد انگشتشو بیشتر اون تو بچرخونه؛ دوماً هر کی نگاه کنه میفهمه که با ملت بی فرهنگ و بی تربیتی طرفه!