Wednesday, 9 December 2015

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

To solve this, Ensure that all your projects used the same version by running the following command in Package manager console of Visual Studio and checking the results:


update-package Newtonsoft.Json -reinstall


Saturday, 5 September 2015

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

You will find fix, from below options:
case 1: when the password is wrong
case 2: when you try to login from some App
case 3: when you try to login from the domain other than your time zone/domain/computer (This is the case in most of scenarios when sending mail from code)
There is a solution for each
solution for case 1: Enter the correct password.
solution for case 2: go to security settings at the followig linkhttps://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps.
solution 1 for case 3: (This might be helpful) you need to review the activity. but reviewing the activity will not be helpful due to latest security standards the link will not be useful. So try the below case.
solution 2 for case 3: If you have hosted your code somewhere on production server and if you have access to the production server, than take remote desktop connection to the production server and try to login once from the browser of the production server. This will add excpetioon for login to google and you will be allowed to login from code.
But what if you don't have access to the production server. try the solution 3
solution 3 for case 3: You have to enable login from other timezone / ip for your google account.
to do this follow the link https://g.co/allowaccess and allow access by clicking the continue button.
And that's it. Here you go. Now you will be able to login from any of the computer and by any means of app to your google account.

Wednesday, 26 August 2015

Difference between == and === in JS

Example:

== only compares values
=== compares values + type

var test1 = '11',
    test2 = 11;

test1 == test2 // true

test1 === test2 // false

Monday, 10 August 2015

How to login using username only without password in MVC using identity membership

Example:

 public async Task<ActionResult> CustomLogin(string name)
        {
            name = "student@gmail.com";

            var user = await UserManager.FindByNameAsync(name);

            if (user != null)
            {

                await SignInManager.SignInAsync(user, true, true);
            }

            return RedirectToAction("Index", "Student");
        }

Monday, 22 June 2015

How to get datatype and length of column in sql server

This query will help:

SELECT column_name as 'Column Name', data_type as 'Data Type',
character_maximum_length as 'Max Length'
FROM information_schema.columns
WHERE table_name = 'YourTableName'

Tuesday, 19 May 2015

How to configure IIS on windows server 2012/ 2012 r2

To enable IIS and the required IIS components on Windows Server 2012/2012 R2, see the instructions below.


  • Use short key Windows+R to open control panel
  • Click on Turn Windows features on or off
  • Open Server Manager and click Manage > Add Roles and Features. Click Next.
  • Select Role-based or feature-based installation and click Next.
  • Select the appropriate server. The local server is selected by default. Click Next.
  • Enable Web Server (IIS) and click Next.
  • No additional features are necessary to install the Web Adaptor, so click Next.
  • On the Web Server Role (IIS) dialog box, click Next.
  • On the Select role services dialog box, verify that the web server components listed below are enabled. Click Next.
  • Verify that your settings are correct and click Install.
  • When the installation completes, click Close to exit the wizard.
It will take some time to get installed, Enjoyyy...... 

Sunday, 10 May 2015

Lock user after number of wrong attempts in MVC 5 using identity 2

First, create a new ASP.NET MVC 5 project and select the Individual User Accounts authentication. Then, install the ASP.NET Idenetity 2 framework using the package manager console.

Next, add the following default value settings in web.config

1
2
3
4
5
<appSettings>
  <add key="UserLockoutEnabledByDefault" value="true" />
  <add key="DefaultAccountLockoutTimeSpan" value="15" />
  <add key="MaxFailedAccessAttemptsBeforeLockout" value="3" />
</appSettings>
By setting UserLockoutEnabledByDefault to true, we are configuring the application to enforce globally that for every user that gets created he/she is subject to lockouts if the user reaches the maximum failed login attempts. Off course, if you do not want to enforce lockouts for particular users such as administrators you can do so when creating their accounts.
The value for DefaultAccountLockoutTimeSpan is in minutes so you can set to what every value you prefer. The example is set to 15 minutes which means if the user reaches the maximum failed login attempts, the user will have to wait for 15 minutes before being allowed to login.
The MaxFailedAccessAttemptsBeforeLockout setting is the number of login attempts you allow the user to retry before a lockout. The example allows 3 attempts after warning the user.
Next, open the IdentityConfig.cs file which is found in the App_Start folder and add the following in the Create method of the ApplicationUserManager class.

1
2
3
4
5
6
7
8
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    // other code removed for brevity      
    manager.UserLockoutEnabledByDefault = Convert.ToBoolean(ConfigurationManager.AppSettings["UserLockoutEnabledByDefault"].ToString());
    manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(Double.Parse(ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
    manager.MaxFailedAccessAttemptsBeforeLockout = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString());
}
It is in the Create method that you configure the lockout settings by refering to the default values set in web.config above.
The final step is to perform the lockout checks and you do that in the POST login action method. So open Account controller and replace it with the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        // find user by username first
        var user = await UserManager.FindByNameAsync(model.Email);
        if (user != null)
        {
            var validCredentials = await UserManager.FindAsync(model.Email, model.Password);
            // When a user is lockedout, this check is done to ensure that even if the credentials are valid
            // the user can not login until the lockout duration has passed
            if (await UserManager.IsLockedOutAsync(user.Id))
            {
                ModelState.AddModelError("", string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
            }
            // if user is subject to lockouts and the credentials are invalid
            // record the failure and check if user is lockedout and display message, otherwise,
            // display the number of attempts remaining before lockout
            else if (await UserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
            {
                // Record the failure which also may cause the user to be locked out
                await UserManager.AccessFailedAsync(user.Id);
                string message;
                if (await UserManager.IsLockedOutAsync(user.Id))
                {
                    message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString());
                }
                else
                {
                    int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);
                    int attemptsLeft =
                        Convert.ToInt32(
                            ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString()) -
                        accessFailedCount;
                    message = string.Format(
                        "Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);
                }
                ModelState.AddModelError("", message);
            }
            else if (validCredentials == null)
            {
                ModelState.AddModelError("", "Invalid credentials. Please try again.");
            }
            else
            {
                await SignInAsync(user, model.RememberMe);
                // When token is verified correctly, clear the access failed count used for lockout
                await UserManager.ResetAccessFailedCountAsync(user.Id);
                return RedirectToLocal(returnUrl);
            }
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}
When a user attempts to login, the first check is to find out if the account is locked out and inform the user accordingly. Then it checks if the user is subject to lockouts and if it does and the credentials are invalid, record the failure(increment the access failed count) and inform the user that he/she has how many more login attempts before account gets locked out. If the account is not locked out and the credentials are valid, then sign the user in and reset the access failed count to zero.
The following shows the message a valid user gets when he/she fails to login the first time

The following shows the message a valid user gets when the account gets locked out

Wednesday, 18 March 2015

How to get lat long from address in C#

We need to install GoogleMaps.LocationServices from the NuGet package. It uses Google's REST API to get lat/long for a given address. Using these you can get latitude and longitude without any need of any API Key.

To install GoogleMaps.LocationServices, either, run the following command in the Package Manger Console.

PM> Install-Package GoogleMaps.LocationServices

Or, search it on Nuget and install it directly

After Install the above package you can use it like this:

Firstly, Add the NameSpace.

using GoogleMaps.LocationServices;

Then use  GoogleLocationService() class to get the latitude and longitude of any given address.

Example:

  /// <summary>
        /// This is to get the lat long from address
        /// </summary>
        public void GetLatLongFromAddress()
        {
            var address = "920 N. Parish Place, Burbank, CA 91506";  
            var locationService = new GoogleLocationService();
            var point = locationService.GetLatLongFromAddress(address);
            var latitude = point.Latitude;
            var longitude = point.Longitude;

        }

Enjoyyy.... :)

Tuesday, 10 March 2015

Create database script with data in Sql Server

Right Click on db => Tasks => Generate Scripts => In "Set Scripting Options: Click Advanced, find Types of data to script. You can choose between Data onlyScript and data and Schema only. The default is Schema only.



Wednesday, 11 February 2015

Convert httppostedfilebase to image in C# and image re-sizing in c#

 private string UploadFile(HttpPostedFileBase postedFile)
        {
            if (postedFile.ContentLength > 0)
            {
                var filename = Path.GetFileName(postedFile.FileName);

                System.Drawing.Image sourceimage =
                    System.Drawing.Image.FromStream(postedFile.InputStream);

                Bitmap newImage = new Bitmap(5, 5);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode = SmoothingMode.HighQuality;
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gr.DrawImage(sourceimage, new Rectangle(0, 0, 5, 5));
                }
            }

}

Wednesday, 4 February 2015

How To Change Password Validation strength in ASP.Net MVC Identity ?

In the MVC project template in VS2013 Update 2, there should be a file called App_Start/IdentityConfig.cs.

In it you should find the class ApplicationUserManager and a static factory method called Create().

That's where the user manager class is configured, including the server-side validation rules for passwords are defined. For example:

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

Note: you can change/customize above configuration for password strength, like this:

// Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };

Enjoyyyy...

Tuesday, 27 January 2015

Query to rename column name in Sql Server 2008

Syntax:

  EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'

Query Example:

  EXEC sp_RENAME 'ExceptionLog.exceptionLog', 'LogMessage', 'COLUMN'


Enjoyyy....

Wednesday, 21 January 2015

Reading App settings from app.config or web.config in .net C#

For Sample App.config like below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

You read the above app settings using code shown below:
using System.Configuration;
You may also need to also add a reference to System.Configuration in your project if there isn't one already. You can then access the values like so:
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
Enjoyyyy.... :)

Wednesday, 14 January 2015

How to calculate difference between two dates in C#

Assuming StartDate and EndDate are of type DateTime:
int dateDifference = (StartDate - EndDate).Days;

Wednesday, 24 December 2014

How to Check if folder exists, if not create it in C#

                string realPath;
                realPath = Server.MapPath("~/ReportHtmlFiles/" + TestFolder + "/");
                // Check if folder exists, if not create it
                if (!Directory.Exists(realPath))
                {
                    Directory.CreateDirectory(realPath);
                }

How to create new folder in mvc 4

var path = Server.MapPath("~/Content/users/" + "NewFolderToAdd/");
Directory.CreateDirectory(path);

                                                            
 
Design by Abhinav Ranjan Sinha