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.

Friday, July 25, 2014

Getting the left section of current Url upto domain name in C#

I was creating product's full links dynamically to do this I need to have the left section of the current URL from http to end of domain name.

Example:

My full link:
http://pro-post.blogspot.in/2014/07/extended-dropdownlistfor-to-create.html

I need: 
http://pro-post.blogspot.in

To achieve this ->

string leftSection = System.Web.HttpContext.Current.Request.Url.OriginalString.Replace(
System.Web.HttpContext.Current.Request.Url.PathAndQuery, "")
leftSection = leftSection.Substring(0, leftSection.LastIndexOf(':'));

ref: Soumyadip [http://soumyadip-cooldips.blogspot.in]

Wednesday, July 16, 2014

Extended DropdownListFor to create colored options

I had a situation to create a drop down list with multicolored options according to some criteria.
Like a dropdown consist of users, suppose users who are Administrator they will be shown in Green, if Restricted User then Red.
I have created this with DropDownListFor, by which it can be implemented easyly in mvc applications.

Steps:
1. Install Nuget package installer in visual studio.
2. Open Nuget Package Console
3. Write- Install-Package DropDownWithColorLegend

Friday, June 27, 2014

Show a perticular element at top of view port using jquery


Requirement:
 Show a particular section on load of the page. only when query string present in URL
 for that page and where div id- showsection exist.


Solution:
  if(document.getElementById("showsection") != null) 
  {
    var str = document.URL.split('?')[1];
    if(str != undefined && str.length>0)
    {
      jQuery("html, body").animate({scrollTop:jQuery("#showsection").offset().top},1000);
    }
  }


In HTML page:
<div id="showsection"></div>
<div id="test">
    test document
</div>

Description:
By placing javascript code in document ready, whole page will be scrolled up and show "test".
You do not have to put anything inside "showsection" div

Monday, June 2, 2014

datagrid - Best Grid Control for ASP.NET MVC

different types of MVC grids

webgrid:
http://jasminewisp.blogspot.in/2013/11/webgrid-in-mvc-3-with-server-side.html
http://www.codeproject.com/Tips/615776/WebGrid-in-ASP-NET-MVC

jqtable
http://www.jtable.org/
http://www.codeproject.com/Articles/277576/AJAX-based-CRUD-tables-using-ASP-NET-MVC-3-and-jTa

grid mvc
http://gridmvc.codeplex.com/

asp.net awesome grid
http://demo.aspnetawesome.com/GridDemo/Grouping

ref:
http://stackoverflow.com/questions/20543265/what-is-the-best-grid-control-for-asp-net-mvc-telerik-devexpress-or-syncfusion
http://newskona.com/5-grid-extension-controls-for-asp-net-web-mvc-application/


Please suggest if you got some more info.

Thursday, May 22, 2014

Calculate distance using google api from searching zip code

I got a list if addresses showed in a list and one search filter containing textbox to insert Zip code.
Now I need to calculate the distance between the filtering Zip code and each address showing in the list. To do this I used google api.
---->
jQuery(document).ready(function () {
  if(jQuery('.atm-zip').children().val().length>0)
  {
   //get the filtering zip value and calculate the distance
    getLatLngFromAddress(jQuery('.atm-zip').children().val()); 
  }
});

var geocoder;
//filtering zip's lat
var p1lt;
//filtering zip's long
var p1ln;

function getLatLngFromAddress(postal_code) {
   if (geocoder == null) {
        geocoder = new google.maps.Geocoder();
    }
    var searchLoc;
    geocoder.geocode({ 'address': postal_code }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            searchLoc = results[0].geometry.location;
            p1lt=searchLoc.lat();
            p1ln=searchLoc.lng();

        }
          jQuery('.atm_list li').each(function(){
            //listed address's lat
            var p2lt=jQuery(this).find('.GeoLat').text();
            //listed address's long
            var p2ln=jQuery(this).find('.GeoLong').text();
           
            jQuery(this).find('.GeoDistance').text(getDistance(p2lt,p2ln) +' mi');                     
          });       
    });
}

var rad = function(x) {
  return x * Math.PI / 180;
};







//this is a function to calculate distance between 2 geographic points
function getDistance(p2lt,p2ln) {
          var R = 6378137; // Earth’s mean radius in meter
          var dLat = rad(p2lt - p1lt);
          var dLong = rad(p2ln - p1ln);
          var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(rad(p1lt)) * Math.cos(rad(p2lt)) *
          Math.sin(dLong / 2) * Math.sin(dLong / 2);
          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
          var d = R * c;
          var resultInMile=d*0.000621371;
          var finalResult=parseFloat(Math.round(resultInMile * 100) / 100).toFixed(2);
          return finalResult; // returns the distance in meter then converted to miles
      }

Wednesday, May 21, 2014

Remove Html tags from a string in Javascript

Strip html tags from a string in javascript. I needed this when I got html formatted address but for google map I required simple address text.

function strip(html)
    {
       var tmp = document.createElement("DIV");
       
        var re = new RegExp('<br>', 'g');
        html = html.replace(re, ' ');
               
        tmp.innerHTML = html;   
       
       
       return tmp.textContent || tmp.innerText || "";
    }


Pass your html string this function will trim the html tags and return it to you. If any break tag present then it will first replace that break with space then send you the text by this way you will find a clean text.

Friday, May 9, 2014

Javascript set location then hard refresh current page and set scroll position to top

I am using tabs in my page, by clicking on a link i need to open next tab in that same window, only by setting a href it is not happening. URL got changed as per #name but 2nd tab is not opening. To get rid of this problem i used following code to hard refresh the page with the new url.

<a onclick="window.scrollTo(0,0);window.location.assign('/page/subpage/#tab2');location.reload(true);" style="cursor:pointer">GO</a>

Here i am first set the current page's scroll position to top, then assign new url after that reload the page. by this way it is opening 2nd tab in the same page but it needs a refresh.

If you have any other idea please share with me.

Allow edmx 4.0 to get view without primary key

Following snippet is to forcefully allow view which do not have any primary key in edmx4.0.

SELECT
  ISNULL(MyPrimaryID,-999) MyPrimaryID,
  NULLIF(AnotherProperty,'') AnotherProperty
  FROM ( ... ) AS temp

ref: http://stackoverflow.com/questions/1013333/entity-framework-and-sql-server-view

Wednesday, April 23, 2014

Get column names of table from SQL Azure

I have multiple Role columns and i need to get all the columns name started with Role,
My database was - SQL Azure
and this is some how different from SQL Server and here i sucked.

I wrote following query:

--select Column_name
--from Information_schema.columns
--where Table_name like 'mytable'
--AND Column_name LIKE '%Role%'


but it was giving error and processor usage become 99%. Then i found "Information_schema" not supported by SQL Azure.

So the rectified query is as follows:

select name as Column_name from sys.all_columns where object_id = (
select object_id from sys.tables where name='mytable')
AND name like '%Role%'



Monday, March 31, 2014

Enable Large file Upload

I was getting error:

Maximum request length exceeded.

while uploading an image of 5 mb, google helped me out to solve this problem. We need to write 2 sections in web.config to get rid of this.

<system.web>
    <httpRuntime maxRequestLength="1048576" /> <!--[value in kb]-->
</system.web>

FOR IIS & or above
<system.webServer>
  <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" /> <!--[value in byte]-->
      </requestFiltering>
    </security>
  </system.webServer>

Now it is allowing me to upload file upto 1 gb.

Web page redirection for mobile devices by checking viewport only

I am facing one scenario where main browser site need to be shown in large devices but for small devices show mobile site.
To do this device profile checking is not enough for me, so need to go with window width.

//under width of 768 mobile site will open.
 if (window.screen.width < 768) {
   window.location = '~/Mobile/Home.aspx'; //for example
 }

//New update : second solution

Now  I extended the functionality, if any desktop page opened in mobile site then that page will be redirected to the mobile version of that page.
NOTE: every desktop page should have their mobile version under "mobile"  folder.

if (window.screen.width < 768)

  var currentPath= location.pathname;
  if(currentPath=='/')
  {
    currentPath="/Home.aspx";
  }
  if((currentPath.indexOf('/mobile/') != -1)||(currentPath.indexOf('/Mobile/') != -1)){
    //console.log("found so no need to redirect");
  }
  else
  {
    //console.log("not found but screen size small so redirect to mobile")
    //console.log('Mobile/'+currentPath);
    window.location = location.protocol +'//'+ location.host+'/Mobile'+currentPath;//Home.aspx
  }
}

Tuesday, February 25, 2014

get column name from column description in mssql

 select
        st.name [Table],
        sc.name [Column],
        sep.value [Description]
    from sys.tables st
    inner join sys.columns sc on st.object_id = sc.object_id
    left join sys.extended_properties sep on st.object_id = sep.major_id
                                         and sc.column_id = sep.minor_id
                                         and sep.name = 'MS_Description'
                                where st.name = 'actBill'
                                AND sep.value = 'aaa'  ---description of the column

Thursday, February 6, 2014

Shorten length of string if it is too large and set ... at the end of sentence or word

I am getting a very large text without any space so it is overflowing parent container, so to manage that situation it will be better if we can calculate the width and trim last part and set ... at the end of the line to show continuation. To do this I have implemented following thing, here if content width is larger than parent width then it will show ... at the end of line and if not then show text as it is. While resizing the window at that time also it will work.

BEST WAY JUST USE CSS

.shortenText {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

<span class="shortenText">test string where ...will come at the end of line if line is very long</span>

Using JQUERY
Here I have user attribute to locate the text container.
Hover the content with ... will show the content in tooltip.

EXAMPLE:

<style type="text/css">
    [autowidth='auto']
    {
        display: none;
    }
</style>

<div style="width:20%">
    <div >
        <div autowidth="auto">abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz</div>      
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
              resizeText();
    });

    $(window).resize(function () {
        resizeText();
    });

 function resizeText() {
        $("[autowidth='auto']").parent().find('.dot').remove()
        $("[autowidth='auto']").parent().find('.resized').remove()

        $("[autowidth='auto']").each(function () {

            var width = $(this).parent().width();
            var childDivWidth = $(this).width();

            var dotwidth = 10;
            var mainContainerCalculatedWidth = width - (dotwidth + 1);
            
            var maindiv = $("<div class='resized'>").text($(this).text()).css('width', mainContainerCalculatedWidth + 'px').css('float', 'left').css('overflow', 'hidden');
            $(this).parent().append(maindiv);

            if (childDivWidth > width) {
                var extra = $("<div class='dot'>").text('...').css('width', dotwidth + 'px').css('float', 'left').attr('title', $(this).text());
                $(this).parent().append(extra);
            }
        });
    }
</script>