Wednesday, 30 December 2015

How to Recursively List All Files and Subfolders Using PowerShell

Here is a simple recursive function to display all file-names with full path in folders and sub-folders. You can only run this command in Windows PowerShell available since the release of Windows 7.
$folder = "c:\\MyDirectory\\"

 Function Upload($item) {
    foreach ($i in Get-ChildItem $item)
    {
        Try
        {
            if((Get-Item $i.FullName) -is [System.IO.DirectoryInfo]){
                  Write-Output $i.FullName
                  Upload($i.FullName)

            }else{
              Write-Output $i.FullName
            }
        }catch{
            Write-Output $i.FullName
        }
    }   
}
 
Upload($folder)

Copy the above code and save in .ps1 file.

December 30, 2015 →

How to Batch Rename All Files in a Folder Using PowerShell

If you are not interested in external programs to renames all files in a folder to lowercase, there is a simple command for you.

- Open Command Prompt (cmd.exe) in Windows
- Go to the directory and run the following command

for /f "Tokens=*" %f in ('dir /l/b/a-d') do (rename "%f" "%f")

Note: This is not a recursive function, it will rename files to lowercase only on the directory where you will run the command.

December 30, 2015 →

Sunday, 8 November 2015

How to Create a Yozio SubLink Using C#

If you need to read more about Yozio Sublink API, here is the documentation http://docs.yozio.com/articles/sublink-apis
Below is a code to create Yozio Sublink.
using System;
using System.Net;
using Newtonsoft.Json;

namespace Yozio
{
    public class YozioResult
    {
        public string status { get; set; }
        public Body body { get; set; }
    }
 
    public class Body
    {
        public string sub_link { get; set; }
        public object link_alias { get; set; }
        public MetaData meta_data { get; set; }
        public long timestamp { get; set; }
    }
 
    public class MetaData
    {
        public string utm_source { get; set; }
        public string utm_medium { get; set; }
        public string utm_campaign { get; set; }
    }
 
    public static class YozioApi
    {
        public static YozioResult SubLink
        {
            get
            {
                const string apiKey = "YOUR-YOZIO-API-KEY";
                const string yozioSuperLink = "YOZIO-SUPER-LINK"; //e.gk7.k.cf

                const string urlString = "http://api.yozio.com/v2.0/?app_key={0}&" +
                                         "method=sub.link.create&" +
                                         "short_url={1}&" +
                                         "reassign_old_alias_to_this_link=true&" +
                                         "meta_data[utm_source]=web&" +
                                         "meta_data[utm_medium]=link&" +
                                         "meta_data[utm_campaign]=blog";

                var url = string.Format(urlString, apiKey, yozioSuperLink);

                var client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                var json = client.DownloadString(new Uri(url));
                var result = JsonConvert.DeserializeObject<yozioresult>(json);
                return result;
            }
        }
    }
}
Usage: Getting Sublink
Yozio.YozioApi.SubLink.body.sub_link;

/Adnan
November 08, 2015 →

Wednesday, 7 October 2015

Wednesday, 9 September 2015

How to Stop Visual Studio 2015 Creating Backup Folders During Project Migration

I was in the process of migrating over to Visual Studio 2015 from Visual Studio 2013. When I executed a local command line build, I received the following error.
Microsoft Visual Studio 2015 Version 14.0.23107.0.
Copyright (C) Microsoft Corp. All rights reserved.
Solution file 'xyz.sln' is from a previous version of this application and must 
be migrated in order to build in this version of the application. 
To migrate the solution, open the solution in this version of the application.
Migration completed successfully, but some warnings were detected during migration.
For more information, see the migration report:  UpgradeLog06.htm
I opened the solution using Visual Studio 2015, and got the migration report. I performed the solution clean followed by solution rebuild and everything works fine. On closing the solution, and performing a local command line build again I got the same error message.
Every time I open the solution using VS 2015 a new "Backup" folder is created with iteration and a new migration report is displayed.
The migration report shows 8 projects that have the following 5 warnings.

Visual Studio needs to make non-functional changes to this project in 
order to enable the project to open in Visual Studio 2015, Visual Studio 2013, 
Visual Studio 2012, and Visual Studio 2010 SP1 without impacting project behavior
The solution I was opening in Visual studio 2015 has around 35 projects and every-time a backup folder is created, it takes space in disk and the make changes in solution file. It was quite a hassle to check-in solution file to source control with backup folder information. So I started digging around how to stop this backup folder nonsense, and after some soul searching I finally fixed it.

Here is the solution:
- Firstly, open your project file (.csproj) in text editor.
- Find the following two lines as shown in the image and delete them.

- Then save the solution file.
Now, open your file in visual studio 2015 again. No more new backup folders and migration reports. It is safe to delete the old backup folders(s) and associated HTML file(s).

/Adnan
September 09, 2015 →

Saturday, 16 May 2015

How to Get Random Items from an Array or List in C#

The simple way to get random item from an Array is to use the return value from random.next(0, array.length) as index to get value from the array.

var randomIndex = random.Next(0, Array.Length);
Console.Write(Array[randomIndex]);
The downside of the above code is it might return you item multiple times (repetition) as we don't keep track of items that we are getting from the source Array.

The easy approach is to consider Array as a deck of cards. We want the items to be 'shuffled' similar to a deck of cards, meaning avoiding any repetition. So we will use  a List<> for the source items, grab them at random and push them to a Stack<> to create the deck of items.

You can create a Stack from anything that is IEnumerable
var stack = new Stack(myList);
See MSDN: http://msdn.microsoft.com/en-us/library/76atxd68.aspx

However, the stack constructor will be using a loop internally, you just don't see it. So for understanding the purpose I will use an example to create Stack with loop.

public static Stack CreateShuffledDeck(IEnumerable values) {

var random = new Random();  var list = new List(values); var stack = new Stack();  while (list.Count > 0) {  // Get the next item at random. var randomIndex = random .Next(0, list.Count); var randomItem = list[randomIndex];  // Remove the item from the list and push it to the top of the deck. list.RemoveAt(randomIndex); stack.Push(randomItem ); }  return stack; } 
Now we have a solution to create a Shuffled Deck. We can now get random items out using Stack.Pop method . Popping something from the stack means "taking the top 'thing'" off the stack.

public static string[] RandomArrayEntries(string[] arrayItems, int count) {
var listToReturn = new List();

if (arrayItems.Length != count) {
var deck = CreateShuffledDeck(arrayItems);

for (var i = 0; i < count; i++) {
var arrayItems= deck.Pop();
listToReturn .Add(item);
}

return listToReturn .ToArray();
}

return arrayItems;
}
We can execute the above code as following:

var countriesArray = new string[] { "Sweden", "Pakistan", "United Kingdom", "Denmark", "Norway", "Finland" };

var newRandomAraay = RandomArrayEntries(countriesArray, 3);

/Adnan
May 16, 2015 →