URL QueryString with Encryption & Decryption

URL QueryString with Encryption & Decryption

For the security concern we have to pass querystring value in encrypted mode,  and while we retrieve querystring value we need to decrypt it and use it.

Here, I mentioned..


  1. Plain text encryption
  2. Decryption of encrypted text
  3. URL encode (System.Web.HttpUtility.UrlEncode)
  4. URL decode (System.Web.HttpUtility.UrlDecode)

Here, I have mentioned URL querystring encryption and decryption...

Encryption

protected void Submit(object sender, EventArgs e)
    {
  string username = "anrorathod";
  string userid = "2279";
        string uname = HttpUtility.UrlEncode(Encrypt(username));
        string uid = HttpUtility.UrlEncode(Encrypt(userid));
        Response.Redirect(string.Format("~/newpagename.aspx?name={0}&id={1}", uname, uid));
    }

    private string Encrypt(string textToEncrypt)
    {
        string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
        byte[] clearBytes = Encoding.Unicode.GetBytes(textToEncrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                textToEncrypt = Convert.ToBase64String(ms.ToArray());
            }
        }
        return textToEncrypt;
    }


Decryption

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
   string username = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
   string userid = Decrypt(HttpUtility.UrlDecode(Request.QueryString["id"]));
        }
    }

    private string Decrypt(string textToDecrypt)
    {
        string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
        textToDecrypt = textToDecrypt.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(textToDecrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                textToDecrypt = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return textToDecrypt;
    }

Hope this will help you and save your time.

Enjoy !!!

:)

Autofac Dependency Injection with Simple Class using MVC Web API

Autofac Dependency Injection with Simple Class using MVC Web API 


Add class library called - Project.Business

Add class - TestSimpleService

public class TestSimpleService
{
 public string GetPing()
 {
  return "simple class called";
 }
}
 


Add WebAPI Project called Project.API

Add nuget packages => Autofac, Autofac.WebApi2 and EntityFramework


Add Controller - TestController

public class TestController : ApiController
{
 TestSimpleService testService;
 public TestController(TestSimpleService _testService)
 {
  testService = _testService;
 }

 [HttpGet]
 [Route("CallSimple")]
 public HttpResponseMessage GetPing()
 {
  var ping = testService.GetPing();
  return Request.CreateResponse(HttpStatusCode.OK, ping);
 }
}
 
 

  

Add class AutofacConfigs.cs

public class AutofacConfigs
{
 public static void Configure()
 {
  var builder = new ContainerBuilder();
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

  //Add Simple class  mapping
   builder.RegisterType<TestSimpleService>().AsSelf().InstancePerRequest();

  var container = builder.Build();
  var resolver = new AutofacWebApiDependencyResolver(container);
  GlobalConfiguration.Configuration.DependencyResolver = resolver;
 }
}
 

  

register this class application start
protected void Application_Start()
{
AutofacConfigs.Configure();
// ... other configuration

}


Run application

Hope this will help you and save your time.

Enjoy !!!

:)

Autofac Dependency Injection with MVC Web API

Autofac Dependency Injection with MVC Web API

Add Class library called - Project.Data

Add Entity Data Model - .edmx and select your database table and add it in edmx fie (For me I am adding Employee table)

Add Interface name => IEmployeeData

public interface IEmployeeData
  {
   List<Employee> GetEmployees();
  }
 

Add Simple class EmployeeData and inherite interface

public class EmployeeData : IEmployeeData
  {
   public List<Employee> GetEmployees()
   {
    List<Employee> employees;
    using (var db = new DemoEntities())
    {
     employees = db.Employees.ToList();
    }
    return employees;
   }
  }
 

  

Add class library called - Project.Business

Add Inteface - IEmployeeService

public interface IEmployeeService
  {
   List<Employee> GetEmployees();
  }



Add Simple class EmployeeData and inherite interface

public class EmployeeService : IEmployeeService
{
 IEmployeeData employeeData;
 public EmployeeService(IEmployeeData _employeeData)
 {
  employeeData = _employeeData;
 }
 public List<Employee> GetEmployees()
 {
  return employeeData.GetEmployees();
 }
}

  

Add WebAPI Project called Project.API

Add nuget packages => Autofac, Autofac.WebApi2 and EntityFramework

Add ConnectionString in web.config file


Add Controller - EmployeeController

public class EmployeeController : ApiController
    {
        IEmployeeService employeeService;
        public EmployeeController(IEmployeeService _employeeService)
        {
            employeeService = _employeeService;
        }

        [HttpGet]
        [Route("employees")]
        public HttpResponseMessage GetEmployees()
        {
            var employees = employeeService.GetEmployees();
            return Request.CreateResponse(HttpStatusCode.OK, employees);
        }
    }
 

  

Add class AutofacConfigs.cs

public class AutofacConfigs
{
 public static void Configure()
 {
  var builder = new ContainerBuilder();
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

  //Add Service mapping
  builder.RegisterType<EmployeeService>().As<IEmployeeService>();

  //Add data mapping
  builder.RegisterType<EmployeeData>().As<IEmployeeData>();

  var container = builder.Build();
  var resolver = new AutofacWebApiDependencyResolver(container);
  GlobalConfiguration.Configuration.DependencyResolver = resolver;
 }
}

 

  

register this class application start
protected void Application_Start()
{
AutofacConfigs.Configure();
// ... other configuration

}


Run application

Hope this will help you and save your time.

Enjoy !!!

:)

SQL Server - Cursor example

SQL Server - Cursor example

Sometimes we need to run loop on data, for that we need cursor. We can write our own business logic in cursor loop. 

Cursor is nothing but it is a loop like development code.

Here, I have mentioned cursor syntax with example. I hope you can use cursor easily as per your requirement...
-- Declare field variable
DECLARE @id INT
DECLARE @fname nvarchar(50)
DECLARE @lname nvarchar(50)
DECLARE @email nvarchar(50)

-- Declare Cursor name
DECLARE @curEmployee CURSOR

-- Set Cursor value
SET @curEmployee = CURSOR FOR
 SELECT id, EmailId, Firstname, LastName FROM Employee

OPEN @curEmployee

-- Loop Cursor
FETCH NEXT
 FROM @curEmployee INTO @id, @email, @fname, @lname
 WHILE @@FETCH_STATUS = 0
 BEGIN
  PRINT convert(nvarchar(10) , @id) + ' - ' + @fname + ' ' + @lname + ' -- ' + @email
  -- TODO
  -- Do your process 
 FETCH NEXT
 FROM @curEmployee INTO @id, @email, @fname, @lname
END

-- Close and deallocate Cursor
CLOSE @curEmployee
DEALLOCATE @curEmployee
 

 


Hope this will help you and save your time.

Enjoy !!!

:)

VSTS - Automation for Azure Function issue

VSTS - Automation for Azure Function issue

I create build Azure function project using VSTS and run successfully. But when I run Release it worked fine for first time, But when I run release next time for the same build definition, it gave me below error.

Error:

Web Deploy cannot modify the file 'DemoApp.DemoFunctions.dll' on the destination because it is locked by an external process. In order to allow the publish operation to succeed, you may need to either restart your application to release the lock, or use the AppOffline rule handler for .Net applications on your next publish attempt. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_FILE_IN_USE. Error count: 1.
 

Solution:

1. Login to Azure portal

2. Goto function app and open your function app
3. Click on "Application settings" from Overview tab.
4. Goto "Application settings" section on "Application settings" page.
5. Add MSDEPLOY_RENAME_LOCKED_FILES = 1
6. Save settings from top left corner.
7. Redeploy your Azure function, it will work.

Hope this will help you and save your time.

Enjoy !!!

:)

Insert - Update SQL Database using Powershell Script

Insert - Update SQL Database using Powershell Script

Here is example of SQL Server database insert and update transaction using Powershell script function


SQL table
CREATE TABLE [dbo].[BackupLog](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [BackupDetail] [nvarchar](500) NOT NULL,
 [StartTime] [datetime] NULL,
 [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



 

 

Insert Record
function InsertRecord($con)
{
 ############  Insert Record  ############
 $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
 $sqlCommand.Connection = $con
 $sqlCommand.CommandText = "SET NOCOUNT ON; " +
  "insert into BackupLog " +
  "VALUES (@BackupDetail,@StartTime,@EndTime); " +
  "SELECT SCOPE_IDENTITY() as [InsertedID]; "

 # Define SQL Parameters 
 $sqlCommand.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@BackupDetail",[Data.SQLDBType]::NVarChar, 500))) | Out-Null
 $sqlCommand.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@StartTime",[Data.SQLDBType]::DateTime2))) | Out-Null
 $sqlCommand.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@EndTime",[Data.SQLDBType]::DateTime2))) | Out-Null
  
 # Set Parameters Value
 $sqlCommand.Parameters[0].Value =  get-date
 $sqlCommand.Parameters[1].Value = get-date
 $sqlCommand.Parameters[2].Value = get-date

 # Run the query and get the scope ID back into $InsertedID
 $InsertedID = $sqlCommand.ExecuteScalar()
 return $InsertedID
}

 

Update Record
function UpdateRecord($con, $recordId)
{
 ############  Update Record  ############
 $sqlCommandUpdate = New-Object System.Data.SqlClient.SqlCommand
 $sqlCommandUpdate.Connection = $con 
 $sqlCommandUpdate.CommandText = "update  BackupLog set  EndTime = @EndTime where id=$recordId " 
  
 # Define SQL Parameters  
 $sqlCommandUpdate.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@EndTime",[Data.SQLDBType]::DateTime2))) | Out-Null
 #$sqlCommand.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@FileLength",[Data.SQLDBType]::BigInt))) | Out-Null
 
 # Set Parameters Value
 $sqlCommandUpdate.Parameters[0].Value = get-date
 
 # Run the query and get the scope ID back into $UpdatedID
 $sqlCommandUpdate.ExecuteScalar() 
}
  

Powershell Script
cls
 
#SQL connection Configuration
$DBServer = "localhost"
$DBName = "DBName"

# Create SQL Connection object
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$DBServer;Database=$DBName;Integrated Security=True;"
$sqlConnection.Open()

# Quit if the SQL connection didn't open properly.
if ($sqlConnection.State -ne [Data.ConnectionState]::Open) 
{
    "There is something wrong in connection string"    
}
else
{

 $newid = InsertRecord -con $sqlConnection 
 # Write to the console.
 "Inserted row ID = $newid"  
 
 #wait for 5 second
 Start-Sleep -s 5
 UpdateRecord -con $sqlConnection -recordId $newid
  
 # Close SQL Connection
 $sqlConnection.Close()
}
  

Hope this will help you and save your time.


Enjoy !!!

:)

Function in Powershell Script

Function in Powershell Script

Here is example of function return value in Powershell script


cls
 
Function Sum($ParamA, $ParamB)
{ 
 Write-Host "ParamA = " $ParamA
 Write-Host "ParamB = " + $ParamB
 $total = $ParamA + $ParamB
 Write-Host "Total = " $total
 return $total
} 

$returnValue = Sum -ParamA 10 -ParamB 15

Write-Host "return value = " $returnValue



 

Hope this will help you and save your time.

Enjoy !!!

:)