Thursday, September 3, 2015

Block or Allow IP in Azure Cloud Service


To block or allow access of IP for your azure cloud service you need to write the following code in ServiceConfiguration.cscfg under </Role> tag:

<NetworkConfiguration>
    <AccessControls>
      <AccessControl name="test">
        <Rule action="permit" description="test" order="100" remoteSubnet="192.72.174.38/32" />
        <!--<Rule action="deny" description="test" order="200" remoteSubnet="0.0.0.0/0" />-->        
      </AccessControl>
    </AccessControls>
    <EndpointAcls>
      <EndpointAcl role="MyApp" endPoint="Endpoint1" accessControl="test"/>
    </EndpointAcls>
    <!--<AddressAssignments>
      <ReservedIPs>
        <ReservedIP name="YourStaticIP"/>
      </ReservedIPs>
    </AddressAssignments>-->
  </NetworkConfiguration>

Here I am allowing a specific IP and denying all IPs this is for my staging site.

Here "MyApp" - is my web role name
and "Endpoint1" - is my endpoint name as in csdef file.
In remoteSubnet="0.0.0.0/0" / section /0 is CIDR notation.

Tuesday, August 11, 2015

Client Side Session Timeout Management

Requirement:
After login if the user is idle for long time then show him a modal window with a count down timer and 2 buttons one for continue and another for logout.

 

Flow:
1. At the ime of page load a timer will be invoked and it will execute at every 10 sec (you can set it by your own).
2. At every movement of mouse or click or keyborad press it will track the last action time on that page.
3. On the basis of last action performed it will calculate the idle time and if the idle time is greater than warning time then it will show the message box.
4. If user remain inactive then after count down it will atomatically take the user to logout page.
5. If user clicks continue then session will be stay active and it will send a request at server side to wake up server session also.

Download:
https://www.nuget.org/packages/ClientSideSessionTimeout/

Direct Install in your project:
PM> Install-Package ClientSideSessionTimeout



Instructions:
Written in a text file inside Instruction folder, you can get this after installing.

Friday, August 7, 2015

Backup and Restore current session

Problem:

I was doing impersonation in my project, from one login user can insert into another person's account this is for admin mainly. here I am facing one problem when the user logged out from 2nd account then I need to repopulate the previous session of the current user. To do so I backed up the current session and store that in a single key after logged in with 2nd user and after log out from 2nd user I get the key and remove current session then restore the session.


Solution:

Backup session store that in a dictionary-
         public Dictionary<string, object> BackupSession()
        {
            Dictionary<string, object> dicSesson = new System.Collections.Generic.Dictionary<string, object>();

            for (int i = 0; i <= HttpContext.Current.Session.Count - 1; i++)
            {
                dicSesson.Add(HttpContext.Current.Session.Keys[i],  HttpContext.Current.Session[i]);
            }

            return dicSesson;
        }


Restore session keys from the dictionary-
        public void RestoreSession(Dictionary<string, object> prevSessionData)
        {
            foreach (string key in prevSessionData.Keys)
            {
                HttpContext.Current.Session[key] = prevSessionData[key];
            }
        }

Sunday, September 21, 2014

Session wrapper c#

Here I am trying to be more lazy.

After spending a lot of time to search in google I have created a wrapper class to handle session keys and values which can full fill my requirements.

My Requirements:
1. Do not want to write Session["nameofkey"], this key name is a text and if I spelled it wrongly then it will not throw any error.
2. I don't want to cast the returned object into my desired type every time.
3. Write less code to handle all of this.


Full Code:
Install from NuGet package, it will set the class "SessionManagement" in your project .
in NuGet search with "Session Wrapper"
OR
Install-Package SessionWrapper


Details:
Created one static class - Session Manager
to set value in session -
public static bool Set(string key, dynamic value)
        {
            HttpContext current = HttpContext.Current;
            if (current == null)
            {
                return false;
            }

            current.Session.Add(key, value);
            return true;
        }

Here I have used value as dynamic variable so any type of data can be passed and it will directly store that data with his type in session.

to get value from session-
 public static dynamic Get(string key, dynamic defaultValue = null)
        {
            HttpContext current = HttpContext.Current;
            if (current == null)
            {
                return defaultValue;
            }

            var valueFromSession = current.Session[key];
            if (valueFromSession != null)
            {
                return valueFromSession;
            }
            return defaultValue;
        }

Here it is returning the value as dynamic datatype so while you are getting value from session it is basically returning you the value with its original type so no need to type cast the value from object to desired type.

Like:
SessionManager.Set("mydate", DateTime.Now);
DateTime d = SessionManager.Get("mydate");

Now to make it easier I created property which can be used as sessionkeys.

Like:
public static int? Session_UserID
        {
            get
            {
                return GetFromSession(MethodBase.GetCurrentMethod());
            }
            set
            {
                SetInSession(MethodBase.GetCurrentMethod(), value);
            }
        }



Here main point is that you just have to copy the getter and setter for all your properties it will be same.

Now to use this just write
SessionManager.Session_UserID = 120;
int? existinguserid = SessionManager.Session_UserID;

It will handle your data storing that in session.
Easy to manage and less error prone.

Tuesday, August 26, 2014

DataAnnotation in models in edmx

In edmx model we have:
namespace DatabaseManager
{
    using System;
    using System.Collections.Generic;
   
    public partial class Item
    {

        public string IDescription { get; set; }
        public string IName { get; set; }

    }
}

If I set DataAnnotation like [Required] on property then it will not persist after edmx update. So it set annotation permanently we have to override meta information this class and merge our custom class with this class.
In our custom model:

namespace DatabaseManager
{
    [MetadataType(typeof(metaClass))]
    public partial class Item
    {

        private class metaClass
        {

            [DisplayName("Description")]
            public string IDescription { get; set; }

            [DisplayName("Name")]
            [Required()]
            public string IName { get; set; }

         }
     }
}

Now you set data annotation in your custom class it will work properly and no need to worry about edmx update.

Tuesday, August 12, 2014

Column level encryption in SQL server 2008r2

USE YourDB
GO

--get the list of keys in current adtabase
select * from sys.symmetric_keys

--get the list of certificates in current database
select * from sys.certificates


--To store encrypted data in the table you have to change the datatype to varbinary(256)


--set the database level encryption password
CREATE MASTER KEY ENCRYPTION
BY PASSWORD = '343k6WJussssszurWi'
GO

--create a certificate by which we are going to encrypt or decrypt data later
CREATE CERTIFICATE EncryptTESTCert
WITH SUBJECT = 'Encrypt
TESTCert'
GO

--create symmetric key by using certificate
CREATE SYMMETRIC KEY
TESTTableKey
WITH ALGORITHM = AES_256 ENCRYPTION
BY CERTIFICATE Encrypt
TESTCert
GO



--EXAMPLE

--Open encryption
OPEN SYMMETRIC KEY
TESTTableKey DECRYPTION
BY CERTIFICATE Encrypt
TESTCert

--encrypt data the show that
DECLARE @ResultVarBinary varbinary(256)              
SET @ResultVarBinary = ENCRYPTBYKEY(KEY_GUID('
TESTTableKey'),'test')  
select @ResultVarBinary

--decrypt data then show that
DECLARE @ResultSTring varchar(max)
SET @ResultSTring = CONVERT(VARCHAR(max),DECRYPTBYKEY(@ResultVarBinary))
select @ResultSTring

--close current encryption
CLOSE SYMMETRIC KEY
TESTTableKey


--NOTE
--Use ENCRYPTBYKEY while You are inserting data
--Use DECRYPTBYKEY When you are fetching data from table



Ref:
http://blog.sqlauthority.com/2009/04/28/sql-server-introduction-to-sql-server-encryption-and-symmetric-key-encryption-tutorial-with-script/


To use it in a easier way I have created separate SP and functions:-


ALTER procedure [dbo].[OpenEncryption]
AS
BEGIN
    OPEN SYMMETRIC KEY TESTTableKey DECRYPTION
    BY CERTIFICATE EncryptPCCASCert
END




ALTER procedure [dbo].[CloseEncryption]
AS
BEGIN
    CLOSE SYMMETRIC KEY
TESTTableKey
END




ALTER FUNCTION [dbo].[EncryptData]
(
    -- Add the parameters for the function here
    @text varchar(max)
)
RETURNS varbinary(256)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar varbinary(256)       
       
    SET @ResultVar = ENCRYPTBYKEY(KEY_GUID('TESTTableKey'),@text)   

    -- Return the result of the function
    RETURN @ResultVar

END




ALTER FUNCTION [dbo].[DecryptData]
(
    -- Add the parameters for the function here
    @text varbinary(256)
)
RETURNS varchar(max)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar varchar(max)       
       
    if @text is null
        begin
            SET @ResultVar =''
        end
    else
        begin
            SET @ResultVar = CONVERT(varchar(max),DECRYPTBYKEY(@text))
        end

    if @ResultVar is null
    BEGIN
        SET @ResultVar = ''
    END
    -- Return the result of the function
    RETURN @ResultVar

END


Sunday, August 3, 2014

ASP.Net 4.5 automatic minification for js and css

To reduce page content size I used asp.net 4.5 default minification system in my MVC 4 web application.
Step 1
 As per step 1 just use-
BundleTable.EnableOptimizations = true;
to minify all bundled js and css with no effort.

Step 2

As per step 2 -
To make it functional set debug="false" in web.config file.