Code -> Break -> Fix -> Blog

Leave a comment

Mettl Coding Test : Find the max. distance between two occurrences of a char in a string

Problem Statement:

  1. Write a method to find the max. distance between two occurrences of a char in a string.
  2. Distance is the no. of unique characters (excluding whitespaces and searched character) between two occurrences of the searched character.

Example 1:

SearchLetter(“my name is granar”, “a”);

Output : 7 (i.e. m,e,i,s,g,r,n)

Example 2:

SearchLetter(“the capital of minnesota is saint paul”, “y”);

Output : -1 (no. occurrence of “y”)

Example 3:

SearchLetter(“quick brown fox jumps over the lazy dog”, “a”);

Output : -1 (only 1 occurrence of “a”)


public static int output1;

public static void SearchLetter(string input1, string input2)
if (string.IsNullOrEmpty(input1)
|| string.IsNullOrEmpty(input2)
|| input1.Count() < 2
|| input2.Count() != 1)
output1 = -1;

var firstIndex = input1.IndexOf(input2);
var lastIndex = input1.LastIndexOf(input2);

if (firstIndex == lastIndex)
output1 = -1;

var distance = lastIndex - firstIndex;
var finalSearchString = input1.Substring(firstIndex + 1, distance - 1);

finalSearchString = finalSearchString.Replace(" ", string.Empty)
.Replace(input2, string.Empty);

string tempString = string.Empty;
string finalString = string.Empty;

foreach (var value in finalSearchString)
if (tempString.IndexOf(value) == -1)
tempString += value;
finalString += value;

output1 = finalString.Count();


Leave a comment

Mettl Coding Test : List the duplicate integers in the array

Problem Statement

  1. Create a method which will list out the duplicate entries in a given integer array.
  2. The input array should have only positive integers.
  3. The method should take 2 parameters, 1st is the count of the array and 2nd the actual array
  4. If no duplicate entries are found then return {-1}.

Example 1 :

DuplicateArray(6, new int[] { 4, 4, 7, 8, 8, 9 });


Example 2:

DuplicateArray(6, new int[] { 4, 4, -7, 8, 8, 9 });


Example 3:

DuplicateArray(7, new int[] { 3, 6, 5, 7, 8, 19, 32 });




public static int[] output1;

public static void DuplicateArray(int input1, int[] input2)
// Validate input1 as it should match with input2.count
// Validate : more than 1 integer present in the array.
// Validate : Positive integers
if (input1 != input2.Count() || input1 &lt; 1
|| input2.FirstOrDefault(x =&gt; x &lt; 0) &lt; 0)
output1 = new int[] { -1 };

List&lt;int&gt; listDuplicateValues = new List&lt;int&gt;();

// Group by numbers and check the count for duplicate entries.
var groups = input2.GroupBy(x =&gt; x);
foreach (var group in groups)
if (group.Count() &gt; 1)

// Validate : if list is empty then set output1 to -1
output1 = listDuplicateValues.Count == 0 ?
new int[] { -1 } : output1 = listDuplicateValues.ToArray();


Leave a comment

Manage Hotmail via Microsoft Office Outlook 2010

A good way to manage your Hotmail or Live account via Office Outlook.

Below are the steps to configure Hotmail account to Microsoft Office Outlook

Download Outlook Hotmail Connector available here

Double click the downloaded setup i.e. OutlookConnector.exe

Accept the terms and click on Install

Installer 1

The setup will do the installation.

Click on Finish

Installer 2.PNG

Open Outlook

Click on File -> Info

Under Account Information, click on Add Account button.

Account 5


In the Add New Account dialog box, select Manually configure server settings or additional server types and click Next.

Account 1.PNG

Select Other and select Microsoft Outlook Hotmail Connector from the list.

Account 2.PNG

Enter user information in the Windows Live Hotmail Settings dialog box. Click Ok.

Account 3

Click Finish to complete the setup.

Account 4.PNG


Hope this helps.


1 Comment

Visual Studio : C# Interactive Window

Recently I came across C# (comeback) feature, Interactive Window, which comes with Visual Studio 2015 Update 1. The interactive Window is a REPL which executes the program piecewise.

You will no longer have to create small ConsoleApplication projects just to try out a small piece of code (bye bye ConsoleApplication42…). With Interactive Window, developers can get output for small code snippets without any project creation,  code file or any assembly. Just type in the code and get the result.

C# Interactive Window is part of Visual Studio which makes it easy to learn new language features and experiment with .NET technologies similar to CShell (not completely) but within Visual Studio.

To open Interactive Window, got to View -> Other Windows and select C# Interactive. As shown below.


Helpful REPL commands to remember before you start:

#help : Display help on specified command, or all available commands and key bindings if none specified.

#clear/#cls : Clears the contents of the editor window, leaving history and execution context intact.

#reset : Reset the execution environment to the initial state, keep history.

As always lets start with Hello World example:

Hello World 1

You can see in the above code, we created 2 strings variables str1 & str2 and wrote the output to the console. Important things to note here, 1. A ‘;’ will make the statement part of the execution context. 2. Pressing ‘Enter’ after the statement without ‘;’ executes the context. Like here it displays the output ‘Hello World’. 3. Even after we got the output the execution context is still intact. So if I execute Console.WriteLine(str1 + str2), the output will be the same. Use #reset command to reset the execution context. 4. No need to specify the namespace.

I can also create a method in the execution context, and use it later. like


I created a method HelloName(string name) and calling it in the same context gets me the desired output but when I reset the execution context and call the method again, an error is displayed stating “The name ‘HelloName’ does not exist in the current context”.

You can also save your script in a file on the disk and can execute it via VS Command Prompt (extension is not important).

Script 1

Script 2

How to reference a DLL and use it
You use the #r directive to reference a DLL.
I have created a simple class library named SimpleMath.dll for easy learning:

Class Library.PNG

Using the #r directive, I can reference my SimpleMath.dll in the Interactive Window’s execution context.
ClassLibrary Reference.PNG

Documentation :
Hope this helps.

Let me know you comments below.



Leave a comment

Print the alphabets which are not part of a given string (C#)

Problem Statement: Print the alphabets which are not part of a given string.


var alpha = new Dictionary&lt;char, bool&gt;();
alpha.Add('a', false);
alpha.Add('b', false);
alpha.Add('c', false);
alpha.Add('d', false);
alpha.Add('e', false);
alpha.Add('f', false);
alpha.Add('g', false);
alpha.Add('h', false);
alpha.Add('i', false);
alpha.Add('j', false);
alpha.Add('k', false);
alpha.Add('l', false);
alpha.Add('m', false);
alpha.Add('n', false);
alpha.Add('o', false);
alpha.Add('p', false);
alpha.Add('q', false);
alpha.Add('r', false);
alpha.Add('s', false);
alpha.Add('t', false);
alpha.Add('u', false);
alpha.Add('v', false);
alpha.Add('w', false);
alpha.Add('x', false);
alpha.Add('y', false);
alpha.Add('z', false);

var inputString = &quot;bhavyajshah&quot;;

foreach(char ch in inputString.ToLower())
alpha[ch] = true;

foreach (var item in alpha)
if (item.Value != true)


VS Templates : User to select NuGet packeges to be pre-installed for Project Template

In my previous blog, I talked about creating a project template, how to pre-install NuGet packages to it and how to use VSIX to deploy the template.

Say, I want to give an option to the end-user to select the NuGet package(s) he/she wants to install from the list of packages availed to her. Lets try to achieve this in this blog.

1. Create a list of all the NuGet packages that you want to provide to the user. And download all the required .nupkg files too. I want to give the below list to the user for selection (This list is just to explain the topic here they may or may not be related).

EntityFramework v6.1.3  (

Newtonsoft.Json v6.0.8 (

Microsoft.Net.Http v2.2.29 (

2. Add all the 3 .nupkg files to the template project and also to .vstemplate so that they are part of the template that will be shipped.


3. Create a wizard that will ask for NuGet package selection. For that we will need to show a dialog to the user to select the items. To do some processing when the template is getting created we need to implement the IWizard interface.

Using the IWizard interface we need to show the NuGet package selection Dialog. Let’s try to achieve this in the following steps.

4. Add a new Console Application project to the solution we created in the previous blog.


5. Create a class under Console Application which will implement IWizard. Add EnvDTE and Microsoft.VisualStudio.TemplateWizardInterface references to get the reference of IWizard and ProjectItem type. Also add a WindowsForm to the same project (required references System.Windows.Form and System.Drawing). I have created ProjectOneWizard.cs class and SelectNugetForm.cs windows form. Form is required to popup a dialog which will have the list of NuGets.


6. IWizard interface has the list of methods that needs to be implemented.

public void RunStarted(object, Dictionary<string, string>, WizardRunKind, object[]) -> Called at the beginning of the template wizard run. The Dictionary holds the standard parameters to be replaced. The last parameter can hold the custom Parameter list.

public void RunFinished() -> Called when the wizard has completed all tasks.

public void BeforeOpeningFile(ProjectItem) -> Called before opening an item in the template. This is related when OpenInEditor is set to true for an item in .vstemplate.

public void ProjectFinishedGenerating(Project) -> Called when a project has finished generating.

public bool ShouldAddProjectItem(string) -> Indicates whether the specified project item should be added to the project.

public void ProjectItemFinishedGenerating(ProjectItem) -> Called when a project item has finished generating. Not relevant for Project Template.

So we will show the Nuget selection Dialog box under RunStarted(…). Here I am showing SelectNugetForm, in this form write the logic which gets the list of Nuget packages to be installed. And under ProjectFinishedGenerting(project) install the packages.

For me I am returning the list of packages as string with semi-colon (;) and the ID & version of the package separated using colon(:) like my return string might be like “Microsoft.Net.Http:2.2.29;Newtonsoft.Json:6.0.8;EntityFramework:6.1.3”. And when I am reading the string I can pull the packageID and it’s version via : and fetching different nugets via ;.

public void RunStarted(object automationObject, 
Dictionary<string, string> replacementsDictionary, 
WizardRunKind runKind, 
object[] customParams)
var selectNugetForm = new SelectNugetForm();
var result = selectNugetForm.ShowDialog();

nugets = result == DialogResult.OK ? 
selectNugetForm.SelectedNuGets : string.Empty;


public void ProjectFinishedGenerating(Project project)
 if (string.IsNullOrEmpty(nugets))

var componentModel = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel)) as IComponentModel;
 if (componentModel == null)

var installer = componentModel.GetService<IVsPackageInstaller>();
 var nuGetList = this.nugets.Split(new char[] { ';' }).Select(nuGet => nuGet.Split(new char[] { ':' }));
 foreach (var nuGetDetails in nuGetList)
 installer.InstallPackage("", project, nuGetDetails[0], nuGetDetails[1], false);

7. Add the wizard extension to .vstemplate file of template project so that when the template is selected by the end-user the wizard that is created in the previous step will get executed.

 <Assembly>ProjectOneTemplateWizard, Version=, Culture=neutral, PublicKeyToken=97d9e18aa34ef2e5</Assembly>

8. Also need to add the Wizard assembly to the VSIX manifest as an asset so that the assembly is shipped correctly.


Thats it!!! Now build the VSIX project & install the extension and try out the new template. To help doing this check out my previous blog.

Let me know your thoughts.


Twitter Logo


VS Templates : Create Visual Studio Project Template with pre-installed NuGet Packages using VS SDK

In this article, I will talk about creating a VS Project Template with pre-installed Nugets and deploying it through VSIX package.

I will start with creating a Visual Studio Project Template. Next will add Nugets to it and at the end with the help of VSIX will deploy the template.

Create VS Project Template using Visual Studio SDK

Download the Visual Studio SDK from here. VS SDK contains templates for creating Item/Project templates as seen below:

New Project Dialog

1. Select C# Project Template from the “Add New Project” dialog. Give appropriate name to your project and Click OK.

2. Generated project will contain a .vstemplate, a .csproj, a .class and an AssemblyInfo.cs file. Of these .vstemplate file, .csproj file and AssemblyInfo.cs files are mandatory. The developer should not delete them but he/she can modify these files.

File List

3. Add new files or modify existing files as per your requirement. Use parameter substitutions where applicable in the newly added files. For more information about Parameter Substitutions see here.

4. Make sure to modify .csproj so that it contains the newly added files or remove the deleted files.

In the figure below, I have removed Class.cs and added 2 new files SampleModel.cs and SampleService.cs. And modified .csproj accordingly.

AddedNewFilesToTemplate                     ModifiedCSProj

5. Also modify the .vstemplate to reflect the changes (Adding SampleModel.cs and SampleService.cs and Deleting Class1.cs entry)


6. Update the Build Action property of each newly added file to None.

7. If required, modify the .ico file to set a new icon for the template.

8. Build the Project, go to /bin folder (debug/release) to get the generated compressed file which will contains the project template.

9. Copy the compressed file (.zip) to the local ProjectTemplate folder from where Visual Studio will pick up the custom templates.

Project Template with Pre-Installed Nuget Package(s)

In the previous step, we have created a ProjectTemplate. Now let’s modify the template so that it has pre-installed NuGet package(s).

1. Download the NuGet package(s) file .nupkg from using the format


2. Add the .nupkg file to your project


3. Modify .vstemplate and add an entry for .nupkg file.


4. Add a reference of the NuGet template Wizard to .vstemplate by adding WizardExtension element. And also the list of NuGet packages that needs to be installed using WizardData element. repository attribute of packages element can have two values template or extension. For now we will use template, I will cover extension later in the series. repository=”template” will look for .nupkg file in the created template (.zip file). You can also add more than one package element under packages element to install more NuGet packages.


5. Build the project and copy the .zip file to the VS template location.

6. Open new instance of Visual Studio and select “New Project”. Select the custom template you created.


7. Click OK. And a new project will be created with the NuGet Package pre-installed.


In this approach the developer who will be using the template will have to explicitly update the package and the template will only install the version that is part of it.

VSIX Packages

Recommended way of deploying the custom project template is through a VSIX package. Because with Visual Studio Extension Manager the end-user can easily get your custom project template, also VS Extension Manager helps push your template update too.

1. Add a new project to the already created Solution above. And select VSIX Project template. Give appropriate name to the project and Click OK.


2. Add the already created Project Template to VSIX. So open source.extension.vsixmanifest file. Goto Assets tab and Click New button to add a new asset. Select Type as Microsoft.VisualStudio.ProjectTemplate and select your Project.


3. Make changes in the Metadata tab if required. Like giving proper description, icon, license details etc.

4. Build the VSIX project to get the output i.e. .vsix file in the output directory.

5. Double-Click on the .vsix file to install the extension.


6. Open a new instance of Visual Studio and goto Tools->Extensions and Updates Dialog-box. Under Installed->Templates you can see the result.


7. You will also get the template which is part of the extension in the New Project dialog.


In the next blog, I will talk about giving the end-user an option to select the NuGet package(s) that they want to pre-install from a list. Also I will talk about how to create solution template.

Let me know your thoughts.


Twitter Logo