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

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

1 Comment

Petrol Pump (Gas station) Problem (C#)

Problem Description:

We have a group of Petrol pump on a Circular Road (Ring Road) say P(1), P(2), P(3)…P(N).

Each Petrol pump has some amount of fuel with it say P(1) has F(1), P(2) has F(2) …. P(N) has F(N).

Distance between two consecutive Petrol pumps are D(1), D(2), D(3) … D(N).So distance between P(1) and P(2) is D(1) and P(2) and P(3) is D(2)…. P(N) and P(1) is D(N).

Find the starting point such that the vehicle should be make the full circle.

static int GetStartPoint(int[] fuel, int[] distance)
if (fuel == null || distance == null || fuel.Length == 0 || distance.Length == 0)
//invalid input.
return -1;

if (fuel.Sum() < distance.Sum())
// No StartPoint found.
return -2;

int startPoint = 0;
int pumpLength = fuel.Length - 1;

int leftOverFuel = 0;
int i = 0;

if (i > pumpLength)
// No StartPoint found.
return -2;

if (fuel[i] + leftOverFuel < distance[i])
startPoint = i++;
leftOverFuel += fuel[i] - distance[i];
if (i == pumpLength)
i = 0;
} while (i != startPoint);

return startPoint + 1;

Leave a comment

Logging to Windows Event Log using Log4Net Utility

1. Install log4net NUGET package.


2. Edit AssemblyInfo.cs

Add the below line in the AssemblyInfo.cs:

[assembly : log4net.Config.XmlConfigurator(Watch=true)]

3. Edit App.config

Add the below <configSections> as the 1st element under <configuration>

 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />

Add the below <log4net> section in app.config

 <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
 <param name="LogName" value="LogginSampleLog" />
 <param name="ApplicationName" value="LoggingSample" />
 <layout type="log4net.Layout.PatternLayout">
 <conversionPattern value="{%level} {%date} – %message%newline" />
 <level value="DEBUG" />
 <appender-ref ref="EventLogAppender" />

4. Add a LogUtility class

static class LoggerUtility
private static ILog logger;

public static ILog Logger
return logger;

public static void InitializeLogger()
if (log4net.LogManager.GetCurrentLoggers().Length == 0)
logger = log4net.LogManager.GetLogger(&quot;EventLogAppender&quot;); // OR logger = log4net.LogManager.GetLogger(typeof(LoggerUtility));
logger.Info(&quot;Begin processing.&quot;);

5. Update registry (Create event source)

As mentioned in here, there are two ways to do this.

  • Update the Windows registry directly
  • Create an Installer using EventLogInstaller class.

6. Lets try it out

class Program

static void Main(string[] args)
LoggerUtility.Logger.Info("Application started.");

string strName = null;

Console.WriteLine("Name : " + strName.ToString());
catch (NullReferenceException nullException)
LoggerUtility.Logger.Error("Name is NULL", nullException);

LoggerUtility.Logger.Info("Application ended.");


After you run the above application, you can see the below output in EventViewer.


Hope this helps.