#Google Analytic Tracker

Pages

Oct 23, 2009

SQL Server – Login failed for user: Error 18456

Every once in awhile I need to reinstall SQL Server. Every time after I reinstall SQL Server and try to run my project executable, I would run into a connection error which says I cannot login with my specific user name.

First – Ensure your Login user is Added

The first thing I would do is to ensure my restored database has the right user.  In fact, it has to be a user from the SQL Server security group, and not the one from the Database security group.

In the following example, the database apts_dev4.0 has a user name call “MentorStreetsDBUser”. Under the DICKYS2\SQLEXPRESS security, it also has “MentorStreetsDBUser”. However, these two users are not the same at all. The one in the database is created by my previous SQLServer. This logon will not work for the newly installed SQLServer.

image

For this part, I simply remove the MentorStreetsDBUser from the database, and add a new user by specifying MentorStreetsDBUser from the SQL Server. This way I should able to logon using this account name. Make sure you give this user the proper security rights.image

But Wait… I still get a Login Fail message with this user!

Second – Ensure SQL Server Authentication Mode is On

This is the part where I usually forgot to do.

Right click on the SQL Server select Property. Click the Security section. You will see the following:

image

In the Server authentication, select both “SQL Server and Windows Authentication mode”

By default, SQL Server only allows Windows Authentication login, and not the SQL Server login. After restart SQLServer, everything will work again.

Conclusion

First, I would hope that SQL Server Management would at least so a warning letting me know that the imported database user would not able to log on.

Second, I think that MS SQL Server should default the Server authentication to both the “SQL Server and Windows Authentication Mode”.

In addition they should provide better error message. I personally don’t see a big security issue if you at least tell the user that "SQL Server Mode Login is not supported”.

Aug 4, 2009

IEnumerable + Linq - Be cautious when you do evaluation the enumerable object

From the last two posts, I emphasised that the evaluation is done each time you access the elements in enumerable object. Because of this, you have to be cautious in the two following situations.

  1. Where clause condition in Linq is modified
  2. Your collections is modified when performing Linq statement

Where Clause has changed example

// keep track on the last record highest mileage
private int _highestMileageRecorded = 10000;

private void GetStatistics(IEnumerable<Vehicle> dataSource)
{
    //Find vehicle with highest mileage compare than the record
    IEnumerable<Vehicle> vehicleExcessHighestMilage
        = from v in dataSource
          where v.Mileage > _highestMileageRecorded 
          select v;

    //Record the highest milage
    _highestMileageRecorded = 
         vehicleExcessHighestMilage.Max(v => v.Mileage);

    Console.Write("Vehicle excesses the records:");   
    foreach (var vehicle in vehicleExcessHighestMilage)
    {
        Console.Write(vehicle.Id + " ");
    }
}

The above code does not work! It will never print out any vehicle id.

The reason is that the variable _highestMileageRecorded has overwritten before I perform the foreach. Remember, this IEnumerable result depends on the current state of Linq statement.

Collection has changed example

Consider the following code: The following code try to correct vehicle that contains incorrect mileage data. Notice that a cache object return a IEnumerable of vehicle that has incorrect mileage. The cache also update itself if any vehicle data changes.

[Test]
public void Test()
{
    List<Vehicle> oVehicleList = new List<Vehicle>();
    GenerateRandomSales(oVehicleList);
    ClearIncorrectMiliage(oVehicleList);
}

private void ClearIncorrectMileage(IEnumerable<Vehicle> dataSource)
{
    VehicleCache vehicleCache = new VehicleCache();
    vehicleCache.LoadData(dataSource);

    IEnumerable<Vehicle> incorrectMileageVehicle = 
        vehicleCache.GetIncorrectMileageVehicle();
    
    foreach (var vehicle in incorrectMileageVehicle)
    {
        //Fix the data
        //Note: Exception occurs 
        vehicle.UpdateMileage(0);
    }
}

private class VehicleCache
{
    List<Vehicle> m_oIncorrectMileageList = new List<Vehicle>();

    public VehicleCache()
    {
        Vehicle.Updated += VehicleUpdated;
    }

    void VehicleUpdated(Vehicle vehicle)
    {
        if (vehicle.Mileage < 0)
            m_oIncorrectMileageList.Add(vehicle);
        else
            m_oIncorrectMileageList.Remove(vehicle);
    }

    public IEnumerable<Vehicle> GetIncorrectMileageVehicle()
    {
        return m_oIncorrectMileageList;
    }
   
    public void LoadData(IEnumerable<Vehicle> oDataSource)
    {
        m_oIncorrectMileageList.AddRange(oDataSource.Where(v => v.Mileage < 0).Select(v => v));
    }
}

If you read run this piece of code, you will most likely get a System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Because the cache try to update itself whenever the data change, it also causes trouble when the code modify the data in a foreach statement. In fact, this could easily occur in a multi-thread application where the cache get modified when other modules looping though the cache. Be sure you lock your collection, or convert the IEnumerable to an list or array before performing operations that affect the cache.

Although the above example seems obvious, it may not be obvious enough in a real application where a developer may not know other module behaviour. Imagine developer A wrote the Cache module, and you got an exception when you use its IEnumerable result. Without checking the code, you may never realized you are modifying the cache indirectly.

Did you increase or decrease your application performance using IEnumerable in Linq (Part 2)?

Last time I talked about how you can improve your application performance by using IEnumerable so that no calculation is performed until you need it.

Bad Performance

Now, consider the following code:

private void GetStatistics(List<Vehicle> totalSaleList)
{
    IEnumerable<Vehicle> toyota
        = from v in totalSaleList
          where v.Make == Make.Toyota
          select v;

    int totalSales = toyota.Count();

    int thisYearSale = 
        (from v in toyota
         where v.Year == 2009
         select v).Count();

    double avgMilage = 
        (from v in toyota
         select v.Millage).Average();

    Console.WriteLine("Total Sales: {0}. This year sale: {1}. Average milage: {2}", totalSales, thisYearSale, avgMilage);
}

Notice that in the above example, I kept the variable "toyota" as an Enumerable. When I try to calculate the “totalSales”, “thisYearSale” and “avgMilage”, the querying always need to re-evaluate the first Linq statement. This is obvious a waste of cpu power. 

Better Performance

Ideally, you should do the following:

private void GetStatistics2(List<Vehicle> totalSaleList)
{
    Vehicle[] toyota
        = (from v in totalSaleList
          where v.Make == Make.Toyota
          select v).ToArray();

    int totalSales = toyota.Length;

    int thisYearSale =
        (from v in toyota
         where v.Year == 2009
         select v).Count();

    double avgMileage =
        (from v in toyota
         select v.Mileage).Average();

    Console.WriteLine("Total Sales: {0}. This year sale: {1}. Average mileage: {2}", totalSales, thisYearSale, avgMileage);
}

By converting the variable “toy ota” into an array, the above code does not need to re-evaluate “toyota” each time when we access the enumerable.

Even Better Performance

If performance is a must, you should try to combine calculations in as less number of loop as possible. Remember, each time you call Linq extension method (i.e. Max(), Min(), Average()), it actually has to loop though your enumerable object to calculate the result.

private void GetStatistics3(List<Vehicle> totalSaleList)
{
    Vehicle[] toyota
        = (from v in totalSaleList
           where v.Make == Make.Toyota
           select v).ToArray();

    int totalSales = toyota.Length;

    int thisYearSale = 0;
    int totalMileage = 0;
    foreach (var vehicle in toyota)
    {
        if (vehicle.Year == 2009)
            thisYearSale++;
        totalMileage += vehicle.Mileage;
    }

    double avgMilage = totalMileage * 1.0 / totalSales;

    Console.WriteLine("Total Sales: {0}. This year sale: {1}. Average milage: {2}", totalSales, thisYearSale, avgMilage);
}

Conclusion

When you need to performance more calculation on the same enumerable object, it would be wise to convert it to a list or an array first before further processing.  This will reduce the time of re-evaluate the enumerable result.