Write C# method that returns DataSet from Stored Procedure

Suppose you are writing a Helper class in your .Net Project that uses ADO.Net in the Data Layer. And you need to call Stored Procedures a lot. Writing a generic Helper method that takes in an Array of SqlParameters can be used so that you don’t have re-write the same code of calling the Stored Procedure again and again.

Below is the code that I’ve used as a general approach to call Stored Procedure and return DataSet:

public static DataSet ExecuteProcedureReturnDataSet(string connString, string procName,
            params SqlParameter[] paramters)
{
	DataSet result = null;
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			using (SqlDataAdapter sda = new SqlDataAdapter(command))
			{
				command.CommandType = System.Data.CommandType.StoredProcedure;
				command.CommandText = procName;
				if (paramters != null)
				{
					command.Parameters.AddRange(paramters);
				}
				result = new DataSet();
				sda.Fill(result);
			}
		}
	}
	return result;
}

Another way to call Stored Procedure would be to return a single value from the Stored Procedure like a string. You can use the below method to return only a String:

public static string ExecuteProcedureReturnString(string connString, string procName,
            params SqlParameter[] paramters)
{
	string result = "";
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			command.CommandType = System.Data.CommandType.StoredProcedure;
			command.CommandText = procName;
			if (paramters != null)
			{
				command.Parameters.AddRange(paramters);
			}
			sqlConnection.Open();
			var ret = command.ExecuteScalar();
			if (ret != null)
				result = Convert.ToString(ret);
		}
	}
	return result;
}

Example of SqlParameter array to be passed to the above methods can be as follows:

SqlParameter[] params =
{
	new SqlParameter("@name", name),
	new SqlParameter("@year", year)
};

How to read connection strings stored in appsettings file C#

This post is based on a setup of an asp.net core application. Configuration is read in the Startup class upon the Application startup. The Configure method in this class calls the ApiBootstrapper to check whether the connection string for Dev or Production is required.
This can be further used to call the Stored Procedures or query tables using ADO.Net.

Appsettings.json file is the asp.net core config file. This file contains the Connection Strings is as shown below:

{
	"configSetting": {
		"ConnectionStrings": {
			"ProdConnection": "Data Source=ServerName;Initial Catalog=DBProd;UID=username;PWD=password;",
			"DevConnection": "Data Source=ServerName;Initial Catalog=DBDev;UID=username;PWD=password;"
		},
		"Parameters": {
			"IsProduction": true
			"IsDev": false
		}
	}
}
public class Startup
{
	public Startup(IConfiguration configuration)
	{
		Configuration = configuration;
	}
	
	public IConfiguration Configuration { get; }
	
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		////
	
	
		ApiBootstrapper.Initialize(Configuration);
	}
	
}

Below is the code for ApiBootstrapper class:

public class ApiBootstrapper
{
	
	public static void Initialize(IConfiguration configuration)
	{
		CommonUtil.IsProduction = configuration.GetSection(ConfigKeys.configSetting.ToString()).GetSection(ConfigKeys.Log.ToString()).Value.ToString();
		if (Convert.ToBoolean(CommonUtil.IsProduction))
		{
			CommonUtil.ConnectionString = configuration.GetSection("configSetting").GetSection("ConnectionStrings").GetSection("ProdConnection").Value.ToString();
		}
	}
}

The above example shows how we can store Connection Strings for different environments like Dev and Prod and read it based on Config file settings.

How to clean uninstall Xcode on Mac

Many times it happens that you update your MacOS and then some new update comes up for the Xcode version and there is a backwards compatibility issue. Then you go to the App Store on your Mac to update the Xcode and Bam! You end up wasting hours because the installation gets stuck. It keeps showing installing for hours. If you force shutdown your MacOS and restart, then again the same story.

This time it happened with me again after I updated MacOS Catalina and installation of Xcode 11.3 just doesn’t end. Stopping in App Store doesn’t work.

Another way is, going to the Launchpad and holding down the alt/option key till all the icons start to jiggle. Then click on the x icon and you’ll be prompted to confirm to delete the Xcode App. Well, this also didn’t work for me. Then restart your Mac to move to the next steps.

Go to the Applications folder and find the Xcode App, right-click on it and move it to Trash/Bin. Empty the Trash/Bin.

For newer versions of Xcode, this step should be sufficient. You can go ahead and re-install Xcode from the App Store.

Removing from the Terminal

You need to run the following command in order to completely remove Xcode:

sudo /Developer/Library/uninstall-devtools --mode=all

The above command requires the admin password for sudo. If you get the error that the above command not found, then it probably doesn’t work for the newer versions of Xcode.

The following folders are cleared with complete uninstallation of Xcode. You might need to consider backing up the data in case you have Projects in the Developer folder and certain preferences to preserve in case you’re reinstalling.

  • /Applications/Xcode.app
  • /Library/Preferences/com.apple.dt.Xcode.plist
  • ~/Library/Preferences/com.apple.dt.Xcode.plist
  • ~/Library/Caches/com.apple.dt.Xcode
  • ~/Library/Application Support/Xcode
  • ~/Library/Developer/Xcode
  • ~/Library/Developer/CoreSimulator

Remove the files at ~/Library/Caches/com.apple.dt.Xcode is basically clearing the cache.

Share your experience on what worked for you to make this post better.

How to Count number of e-mails in mailbox using PowerShell

First, you need to access the mailbox on the Microsoft Exchange Server and then get the mailbox statistics for the count of e-mails. The credentials you use should have admin access on the Server to be able to access the mailbox.

The following script uses some credentials stored in a file on the machine where the script is running and connects to a Session on the Microsoft Exchange Server:

$un = “admin@somedomain.com”
$Pass = cat “C:\Data\Securestring.txt” | ConvertTo-SecureString
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Un, $Pass

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://{servername}/PowerShell/ -Authentication Kerberos -Credential $Credentials

Import-PSSession $Session -DisableNameChecking

$data=Get-MailboxFolderStatistics -Identity "somemail@somedomain.com" -FolderScope inbox | ?{$_.folderpath -eq "/inbox"} | select ItemsInFolder 

Write-Host $data.ItemsInFolder

You can further use this data item to mail it to the Admins for Operations purpose.

To know how to send e-mail in PowerShell, check out this post here.

Configure Reverse Proxy in IIS with URL Rewrite

Reverse Proxy is an intermediate Server that might be exposed to the Internet that can help secure your incoming traffic from the Client and forwarding the request to a back-end service that might be on a Private network. This returns the response back to the Client and hides your Web Server from the Outside world.

You need the following IIS extensions for configuring IIS Reverse Proxy:

URL Rewrite:
https://www.iis.net/downloads/microsoft/url-rewrite

Application Request Routing:
https://www.iis.net/downloads/microsoft/application-request-routing

Now add the following URL Rewrite rule:

You’ll be prompted to enable the ARR to further enable Proxy functionality. Click on OK.

In the above window, you can also provide the Outbound configuration to map the response URLs From Private URL To Public URL conversions mapping.

For this example, accessing http://localhost:8087 will simply redirect to http://localhost:8084 and serve the Client.

Use package react-svg-radar-chart to create Radar chart ReactJS

Create a basic ReactJS App using the create-react-app Post here.

Our final aim is to generate a Radar Chart using the npmjs package react-svg-radar-chart. Also, the dot markings on the chart should be able to show the current index and key, values on the chart on Hover as shown below.

The code is available in my Github profile.

Install the Package in your Project by running the following command in the Terminal:

npm install react-svg-radar-chart

Replace the code for the index.js file as shown below:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

Create the App.js file for the App component and add the below code:

import React, { Component } from "react";
import MyComp from "./MyComp";
import MyRadarComp from "./MyRadarComp";

export default class App extends Component {
    render() {
        return (
          <div className="App">
            <MyRadarComp />
          </div>
        );
      }
}

Create MyRadarComp.js file and add the below code:

import React from 'react';
 
import RadarChart from 'react-svg-radar-chart';
import 'react-svg-radar-chart/build/css/index.css'
 
export default class MyRadarComp extends React.Component {
  render() {
    const tooltipstyle = {
        position: 'relative',
        display: 'inline-block',
        borderBottom: '1px dotted black'
    }

    const tooltiptextstyle = {
        visibility: 'hidden',
        width: '220px',
        backgroundColor: 'black',
        color: '#fff',
        textAlign: 'center',
        borderRadius: '6px',
        padding: '5px 0',
    
        /* Position the tooltip */
        position: 'absolute',
        zIndex: '1',
    }

 	 const data = [
      {
        data: {
          battery: 0.5,
          design: .7,
          useful: 0.985,
          speed: 0.57,
          weight: 0.7
        },
        meta: { color: 'blue' }
      },
      {
        data: {
          battery: 0.6,
          design: .85,
          useful: 0.5,
          speed: 0.6,
          weight: 0.7
        },
        meta: { color: 'red' }
      },
      {
            data: {
              battery: 0.7,
              design: .8,
              useful: 0.9,
              speed: 0.67,
              weight: 0.8
            },
            meta: { color: '#58FCEC' }
        }
    ];
 
    const captions = {
      // columns
      battery: 'Battery Capacity',
      design: 'Design',
      useful: 'Usefulness',
      speed: 'Speed',
      weight: 'Weight'
    };

    const noSmoothing = points => {
        let d = 'M' + points[0][0].toFixed(4) + ',' + points[0][1].toFixed(4);
        for (let i = 1; i < points.length; i++) {
          d += 'L' + points[i][0].toFixed(4) + ',' + points[i][1].toFixed(4);
        }
        return d + 'z';
      };
       
      const defaultOptions = {
        size: 200,
        axes: true, // show axes?
        scales: 3, // show scale circles?
        captions: true, // show captions?
        captionMargin: 10,
        dots: true, // show dots?
        zoomDistance: 1.2, // where on the axes are the captions?
        setViewBox: (options) => `-${options.captionMargin} 0 ${options.size + options.captionMargin * 2} ${options.size}`, // custom viewBox ?
        smoothing: noSmoothing, // shape smoothing function
        axisProps: () => ({ className: 'axis' }),
        scaleProps: () => ({ className: 'scale', fill: 'none' }),
        shapeProps: () => ({ className: 'shape' }),
        captionProps: () => ({
          className: 'caption',
          textAnchor: 'middle',
          fontSize: 10,
          fontFamily: 'sans-serif'
        }),
        dotProps: () => ({
          className: 'dot',
          mouseEnter: (dot) => { 
              document.getElementById("tooltip").innerText = "index: " + dot.idx + ", key: " + dot.key + ", value: " + dot.value;
              document.getElementById("tooltip").style.visibility = "visible";
            },
          mouseLeave: (dot) => { 
              document.getElementById("tooltip").innerText = "";
              document.getElementById("tooltip").style.visibility = "hidden";
            }
        })
      };
 
    return (
      <div>
        <RadarChart
            captions={{
              // columns
              battery: 'Battery Capacity',
              design: 'Design',
              useful: 'Usefulness',
              speed: 'Speed',
              weight: 'Weight'
            }}
            data={data}
            size={400}
            options={defaultOptions}
          />
          <div id="divtool" style={tooltipstyle}><label id="tooltip" style={tooltiptextstyle}></label></div>
        </div>
    );
  }
}

Run the Project:

npm start

A few points about the MyRadarComp component:

  1. The code is taken from the npmjs package sample provided in the package description.
  2. I’ve modified the css a bit to show the dots on the chart and also show the values on the Hover event of the dots.
  3. The caption labels and the data property names should match in order to correctly display the data.

Setup Github Repo from Visual Studio Code

  1. Create the Project or directory on your file system. My local folder is called formik-sample. You can also create using the create-react-app Post here for a sample ReactJS App.
  2. Create a repository on Github. I’ve named it sample-form-reactjs.
  3. Click on Clone or Download. Copy the SSH link.
  4. Open the local folder in VS Code as created in Step 1.
  5. In the Terminal Window in VS Code, type the following commands:
  6. git config –global user.name someid
  7. git clone git@github.com:someid/sample-form-reactjs.git
  8. After this is done, just follow the same steps for git stage/commit/push etc.

For # 3:

However, if Step 5. gives error like below:

Check your network firewall settings if you’re doing it from Office. Try it out from your home and it should work.

Also, you can clone git@github which is SSH version but for that you have generate ssh keys and have to set it in local environment and if you don’t want to set up that then just use https version in the above clone command.

If you face branch related errors, since you might have already created a repo on Github, you can create a new branch as below:

git checkout -b some-sample

Then push the changes to the new branch:

git push --set-upstream origin some-sample