How to detect browser name and version using javascript or jquery in asp.net

<html>
<head>
 <script>
 navigator.sayswho = (function () {
 var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
 
 if (/trident/i.test(M[1])) {
 tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
 //return 'IE ' + (tem[1] || '');
 return { name: 'IE ', version: (tem[1] || '') };
 }
 
 if (M[1] === 'Chrome') {
 tem = ua.match(/\bOPR\/(\d+)/);
 //if (tem != null) return 'Opera ' + tem[1];
 if (tem != null) { return { name: 'Opera', version: tem[1] }; }
 }
 
 M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];

 if ((tem = ua.match(/version\/(\d+)/i)) != null) {
 M.splice(1, 1, tem[1]);
 }
 alert('Browser Name: ' + M.join(' and Version # '));
 return M.join(' ');
 })();
 </script>
</head>
</html>

Copy above code and paste it into notepad and save notepad as .html file. Now open .html file and you will see the result.

http://www.codeproject.com/Answers/898796/How-to-get-browser-name-in-javascript-or-jquery-in#answer2

Detecting a mobile browser

In the growing mobile internet world, it is necessary to make your application mobile browser friendly.

I am working on client project where client has some specific requirement when application is open in mobile device browser. I have to show/hide CSS class based on browser detection. I was googling for solution to detect mobile device/browser using JavaScript or jQuery. I found the solution which works great for me.

Source: http://www.abeautifulsite.net/detecting-mobile-devices-with-javascript/

Github: https://github.com/kaimallea/isMobile

Minified version of script included in the HTML since it’s <1kb.

<script>
// Minified version of isMobile included in the HTML since it’s <1kb
(function(i){var e=/iPhone/i,n=/iPod/i,o=/iPad/i,t=/(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,r=/Android/i,d=/BlackBerry/i,s=/Opera Mini/i,a=/IEMobile/i,b=/(?=.*\bFirefox\b)(?=.*\bMobile\b)/i,h=RegExp(“(?:Nexus 7|BNTV250|Kindle Fire|Silk|GT-P1000)”,”i”),c=function(i,e){return i.test(e)},l=function(i){var l=i||navigator.userAgent;this.apple={phone:c(e,l),ipod:c(n,l),tablet:c(o,l),device:c(e,l)||c(n,l)||c(o,l)},this.android={phone:c(t,l),tablet:!c(t,l)&&c(r,l),device:c(t,l)||c(r,l)},this.other={blackberry:c(d,l),opera:c(s,l),windows:c(a,l),firefox:c(b,l),device:c(d,l)||c(s,l)||c(a,l)||c(b,l)},this.seven_inch=c(h,l),this.any=this.apple.device||this.android.device||this.other.device||this.seven_inch},v=i.isMobile=new l;v.Class=l})(window);

// My own arbitrary use of isMobile, as an example
(function () {
var MOBILE_SITE = ‘/mobile/index.html’, // site to redirect to
NO_REDIRECT = ‘noredirect'; // cookie to prevent redirect

// I only want to redirect iPhones, Android phones and a handful of 7″ devices
if (isMobile.apple.phone || isMobile.android.phone || isMobile.seven_inch) {

// Only redirect if the user didn’t previously choose
// to explicitly view the full site. This is validated
// by checking if a “noredirect” cookie exists
if ( document.cookie.indexOf(NO_REDIRECT) === -1 ) {
document.location = MOBILE_SITE;
}
}
})();
</script>

Happy Coding :)

Generating Unique Key in .Net using RNGCryptoServiceProvider

I need to create some unique keys. GUID is one option as they give Globally Unique identifier but they are big. If you want to issue unique number in your application which you want to give as AppKey or any reference number then GUIDs is obviously not a solution.

RNG means Random Number Generator

The .net Framework provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers.

Although we can use this class to generate unique number in some sense. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only.

So, we used this function along with some character masking to generate unique key of any length (here I take 32 character long key).

Below is code sample:

private string RNGCharacterMask()

{

int maxSize = 32;

int minSize = 32;

char[] chars = new char[62];

string a;

a = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890″;

chars = a.ToCharArray();

int size = maxSize;

byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);

size = maxSize;

data = new byte[size];

crypto.GetNonZeroBytes(data);

StringBuilder result = new StringBuilder(size);

foreach (byte b in data)

{

result.Append(chars[b % (chars.Length – 1)]);

}

return result.ToString();

}

Happy Coding… :)

Prevent Cross-Site Request Forgery (CSRF) using ASP.NET anti-forgery token

The anti-forgery token used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect. It generates a hidden  field (anti-forgery token) that is validated when the form is submitted.

To generate the AntiForgeryToken and the Cookie on the client side, we declare it as follows in the HTML form in the user.cshtml

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<fieldset>
<legend>UserDetails</legend>

This ensures that a form being posted to the server was actually generated by the same server. Thus fake forms that do not have the AntiForgeryToken from the correct server, gets rejected.

To validate an incoming post request, add the [ValidateAntiForgeryToken] filter to your target action method.

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Assuming that everything is going well, the request goes through as normal. But if not, there’s an authorization failure with message  “A required anti-forgery token was not supplied or was invalid”.

In case you want to protect multiple forms in your application independently of each other, you can use a “salt” value when you call Html.AntiForgeryToken()…

HTML Code:

<%= Html.AntiForgeryToken(“someString”) %>

Controller Code:

[ValidateAntiForgeryToken(Salt=”someString”)]
public ViewResult SubmitUpdate()
{
// Your code goes here…
}

Salt can be any non empty string.

A different salt value means a different anti-forgery token will be generated.

In conclusion, ASP.NET MVC’s AntiForgeryToken helpers are easy to use, and work very nicely!

Thank you!

Happy Coding :)

asp.net mvc

asp.net mvc

The efficient way to generate 4 or 8 characters long random alphanumeric string in SQL

SELECT LEFT(CONVERT(VARCHAR(36),NEWID()),4)+RIGHT(CONVERT(VARCHAR(36),NEWID()),4)

SELECT RIGHT(REPLACE(CONVERT(VARCHAR(36),NEWID()),’-‘,”),8)

DECLARE @chars NCHAR(36)
SET @chars = N’0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ’
DECLARE @result NCHAR(5)
SET @result = SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
            + SUBSTRING(@chars, CAST((RAND() * LEN(@chars)) AS INT) + 1, 1)
SELECT @result

 

In order to ensure uniqueness for each varchar you can store the results in a table and compare with result in that table. You can also make the varchar longer and just hope for the best.

Happy Coding :)