Abhi's den...

The piece of code which nobody cracked...
Creating a secure SQL server login - CHECK_EXPIRATION & CHECK_POLICY

In SQL Server you can create users using T-SQL or using the options provided by SQL Server Management Studio.

 

Create user sql server

 

CREATE LOGIN sql_user WITH PASSWORD ='sql_user_password' MUST_CHANGE,

DEFAULT_DATABASE = defDB,

CHECK_EXPIRATION = ON,

CHECK_POLICY = ON

As mentioned in the previous article (http://weblogs.asp.net/cabhilash/archive/2010/04/07/login-failed-for-user-sa-because-the-account-is-currently-locked-out-the-system-administrator-can-unlock-it.aspx) when CHECK_POLICY = ON user account follows the password rules provided in the system on which the SQL server is installed.

When MUST_CHANGE keyword is used user is forced to change the password when he/she tries to login for the first time.

CHECK_EXPIRATION and CHECK_POLICY are only enforced on Windows Server 2003 and later.

If you want to turn off the password expiration enforcement or security policy enforcement, you can do by using the following statements. (But these wont work if you have created your login with MUST_CHANGE and user didn't change the default password)

ALTER LOGIN sql_login WITH CHECK_EXPIRATION = OFF

go

ALTER LOGIN sql_login WITH CHECK_POLICY = OFF

Posted: Apr 07 2010, 03:58 PM by cabhilash | with 2 comment(s)
Filed under:
Login failed for user 'sa' because the account is currently locked out. The system administrator can unlock it.

Login failed for user 'sa' because the account is currently locked out. The system administrator can unlock it. (Microsoft SQL Server, Error: 18486)

SQL server has local password policies. If policy is enabled which locks down the account after X number of failed attempts then the account is automatically locked down.This error with 'sa' account is very common. sa is default administartor login available with SQL server. So there are chances that an ousider has tried to bruteforce your system. (This can cause even if a legitimate tries to access the account with wrong password.Sometimes a user would have changed the password without informing others. So the other users would try to lo)

You can unlock the account with the following options (use another admin account or connect via windows authentication)

    Alter account & unlock

    ALTER LOGIN sa WITH PASSWORD='password' UNLOCK

    Use another account

    Almost everyone is aware of the sa account. This can be the potential security risk. Even if you provide strong password hackers can lock the account by providing the wrong password. ( You can provide extra security by installing firewall or changing the default port but these measures are not always practical). As a best practice you can disable the sa account and use another account with same privileges.

ALTER LOGIN sa DISABLE

You can edit the lock-ot options using gpedit.msc( in command prompt type gpedit.msc and press enter). Navigate to Account Lokout policy as shown in the figure

Group policy

The Following options are available

Account lockout threshold

This security setting determines the number of failed logon attempts that causes a user account to be locked out. A locked-out account cannot be used until it is reset by an administrator or until the lockout duration for the account has expired. You can set a value between 0 and 999 failed logon attempts. If you set the value to 0, the account will never be locked out.

Failed password attempts against workstations or member servers that have been locked using either CTRL+ALT+DELETE or password-protected screen savers count as failed logon attempts.

Account lockout duration

This security setting determines the number of minutes a locked-out account remains locked out before automatically becoming unlocked. The available range is from 0 minutes through 99,999 minutes. If you set the account lockout duration to 0, the account will be locked out until an administrator explicitly unlocks it.

If an account lockout threshold is defined, the account lockout duration must be greater than or equal to the reset time.

Default: None, because this policy setting only has meaning when an Account lockout threshold is specified.

Reset account lockout counter after

This security setting determines the number of minutes that must elapse after a failed logon attempt before the failed logon attempt counter is reset to 0 bad logon attempts. The available range is 1 minute to 99,999 minutes.

If an account lockout threshold is defined, this reset time must be less than or equal to the Account lockout duration.

Default: None, because this policy setting only has meaning when an Account lockout threshold is specified.

When creating SQL user you can set
CHECK_POLICY=on which will enforce the windows password policy on the account. The following policies will be applied

Define the Enforce password history policy setting so that several previous passwords are remembered. With this policy setting, users cannot use the same password when their password expires. 

Define the Maximum password age policy setting so that passwords expire as often as necessary for your environment, typically, every 30 to 90 days. With this policy setting, if an attacker cracks a password, the attacker only has access to the network until the password expires. 

Define the Minimum password age policy setting so that passwords cannot be changed until they are more than a certain number of days old. This policy setting works in combination with the Enforce password historypolicy setting. If a minimum password age is defined, users cannot repeatedly change their passwords to get around the Enforce password history policy setting and then use their original password. Users must wait the specified number of days to change their passwords. 

Define a Minimum password length policy setting so that passwords must consist of at least a specified number of characters. Long passwords--seven or more characters--are usually stronger than short ones. With this policy setting, users cannot use blank passwords, and they have to create passwords that are a certain number of characters long. 

Enable the Password must meet complexity requirements policy setting. This policy setting checks all new passwords to ensure that they meet basic strong password requirements. 

Password must meet the following complexity requirement, when they are changed or created:

Not contain the user's entire Account Name or entire Full Name. The Account Name and Full Name are parsed for delimiters: commas, periods, dashes or hyphens, underscores, spaces, pound signs, and tabs. If any of these delimiters are found, the Account Name or Full Name are split and all sections are verified not to be included in the password. There is no check for any character or any three characters in succession.

Contain characters from three of the following five categories: 

English uppercase characters (A through Z)

English lowercase characters (a through z)

Base 10 digits (0 through 9)

Non-alphabetic characters (for example, !, $, #, %)

A catch-all category of any Unicode character that does not fall under the previous four categories. This fifth category can be regionally specific.

 

 

 

Calling Web Services in classic ASP

 Last day my colleague asked me the provide her a solution to call the Web service from classic ASP. (Yes Classic ASP. still people are using this :D )

We can call web service SOAP toolkit also. But invoking the service using the XMLHTTP object was more easier & fast.

To create the Service I used the normal Web Service in .Net 2.0 with [Webmethod]


public class WebService1 : System.Web.Services.WebService

{

[WebMethod]

public string HelloWorld(string name)
{
return name + " Pay my dues :) "; // a reminder to pay my consultation fee :D
}

}


In Web.config add the following entry in System.web
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

Alternatively, you can enable these protocols for all Web services on the computer by editing the <protocols> section in Machine.config. The following example enables HTTP GET, HTTP POST, and also SOAP and HTTP POST from localhost:

<protocols>

<add name="HttpSoap"/>

<add name="HttpPost"/>

<add name="HttpGet"/>

<add name="HttpPostLocalhost"/>

<!-- Documentation enables the documentation/test pages -->

<add name="Documentation"/>

</protocols>


By adding these entries I am enabling the HTTPGET & HTTPPOST (After .Net 1.1 by default HTTPGET & HTTPPOST is disabled because of security concerns)

The .NET Framework 1.1 defines a new protocol that is named HttpPostLocalhost. By default, this new protocol is enabled. This protocol permits invoking Web services that use HTTP POST requests from applications on the same computer. This is true provided the POST URL uses http://localhost, not http://hostname. This permits Web service developers to use the HTML-based test form to invoke the Web service from the same computer where the Web service resides.


Classic ASP Code to call Web service

<%Option Explicit

  1. Dim objRequest, objXMLDoc, objXmlNode

  2. Dim strRet, strError, strNome

  3. Dim strName

  4. strName= "deepa"

  5. Set objRequest = Server.createobject("MSXML2.XMLHTTP")

  6. With objRequest

  7. .open "GET", "http://localhost:3106/WebService1.asmx/HelloWorld?name=" & strName, False

  8. .setRequestHeader "Content-Type", "text/xml"

  9. .setRequestHeader "SOAPAction", "http://localhost:3106/WebService1.asmx/HelloWorld"

  10. .send

  11. End With

  12. Set objXMLDoc = Server.createobject("MSXML2.DOMDocument")

  13. objXmlDoc.async = false

  14. Response.ContentType = "text/xml"

  15. Response.Write(objRequest.ResponseText)

  16. %>


In Line 6 I created an MSXML XMLHTTP object.

Line 9 Using the HTTPGET protocol I am openinig connection to WebService

Line 10:11 – setting the Header for the service

In line 15, I am getting the output from the webservice in XML Doc format & reading the responseText(line 18).

In line 9 if you observe I am passing the parameter strName to the Webservice You can pass multiple parameters to the Web service by just like any other QueryString Parameters.

In similar fashion you can invoke the Web service using HTTPPost. Only you have to ensure that the form contains all th required parameters for webmethod.

 

Happy coding !!!!!!!

Extension Methods - add methods to class

 

Consider the following class

  public class Person

    {

        public string FirstName { get; set; }

        private string LastName { get; set; }

        protected string Email { get; set; }

        public int Age { get; set; }

       virtual public void showName()

        {

            Console.WriteLine("base class");

        }

    }



To add additional methods to a class you have to subclass it or add the function directly to the class. If the class is sealed then you will have very limited options only.


In C#, you can use the new extension method feature to add a new method to an existing type. To add the method to the existing class, define a new static class and define the

extension method (a static method) within it like the following


    static class ExtensionMethods

    {

        public static string AddMarks(this Person per,double marks1, double marks2)

        {

            return (marks1 + marks2).ToString();

        }

    }


The first parameter of an extension method is prefixed by the this keyword, followed by the type it is extending (Person in this example, indicating to the compiler that this extension method must be added to the Person class). The rest of the parameter list (if any) is then the signature of the extension method.


(In the figure you can see the new extension method for the Person object )

If an extension method has the same signature as another method in the class it is trying to extend, the method in the class will take precedence and the extension method will be ignored.

http://thetechjungle.blogspot.com/

Posted: Feb 13 2010, 11:13 PM by cabhilash | with no comments
Filed under: ,
DataTable to Dictionary using LINQ

Sometimes we have to create generic dictionary from the values in datatable. Usually we will loop through all the rows in the datatable and add the relevant keys to dictionary object

 

for (int _iExRowCnt = 0; _iExRowCnt < dsReturn.Tables[0].Rows.Count; _iExRowCnt++)

{

//add some code to chek null values & other validations if any

_dictObj.Add(dsReturn.Tables[0].Rows[iExRowCnt][0].dsReturn.Tables[0].Rows[iExRowCnt][1]);

}

 

After LINQ was introduced there better way of doing the same addition.
In the following code i am creating a datatable and populaing few dummy records.

DataTable dtTable = new DataTable();dtTable.Columns.Add(new DataColumn("ColumnNo", typeof(System.String)));
dtTable.Columns.Add(
new DataColumn("controlType", typeof(System.String)));
dtTable.Columns.Add(
new DataColumn("showVal", typeof(System.Boolean)));

 

DataRow dr;

for (int i = 0; i < 10; i++)
{
dr = dtTable.NewRow();
dr[0] = dtTable.Rows.Count + 1;
dr[1] = i.ToString() +
"Value";
dr[2] =
false;
dtTable.Rows.Add(dr);
}

//In the following code I am using LINQ to create a new Dictionary<string,string>

//You can filter the data and checf for the conditions in data which you dont want in dictionary

 

var dic = (from order in dtTable.AsEnumerable()

where order.Field<Boolean>("showVal") == false

select new

{

myColumnNo = order.Field<
String>("ColumnNo"),myControlType = order.Field<String>("controlType")

}).AsEnumerable().ToDictionary(k => k.myColumnNo, v => v.myControlType);

 

This code snippet uses Enumerable.ToDictionary Method
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx

var dic will hold Dictionary<string,string> object. In the sample code it will have 10 elements

 For further reading

Posted: Dec 28 2009, 02:35 PM by cabhilash | with 4 comment(s) |
Filed under: , ,
Anonymous types for dummies
Anonymous types are used to define strong types without defining the type. Anonymous types are strongly typed and checked at compile time. It provides a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object. This type is widely used by LINQ, because LINQ returns dynamically-shaped data, whose type is determined by the LINQ query



To understand better look at the following code
static void Main(string[] args)
        {
               string[] names = { "Abhi1", "abhi", "abhi11", 
                       "george", "bush", "britney", 
                       "gandhi", "David" };

            
             IEnumerable<string> varAnnoyType = from str in names 
                                         orderby str
                                         select str;

            //following code also valid
          //var varAnnoyType = from str in names 
          //                               orderby str
          //                               select str;

             foreach (string strname in varAnnoyType)
                 Console.WriteLine(strname);


                    Console.ReadLine();
                                      
        }

anonymous type is an object which supports IEnumerable interface. 

In the above example an array of names is created (took the array collection from msdn) , anIEnumerable<string> type is created, see the keyword like from used to iterate eact item in collection, orderby clause orders (without LINQ imagine the dictionaries , temp variables and other techniqies used to sort items now this is really cool). You can add a Where clause also before the select keyword. If any conditions are specified then select will retrieve only those items which satisfies the where clause.

  var varAnnoyType = from str in names
                                where str.StartsWith("abhi")
                                orderby str
                                select str;

The for each iteration can be written like the following also.
foreach (var strname in varAnnoyType)
                 Console.WriteLine(strname);

If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.

An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Anonymous types cannot contain unsafe types as properties.

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
LINQ for dummies - an overview

Why do we need LINQ?


Most of us would have wrote code to access data from different data sources a database, in memory objects , XML files or from other formats. We have different guidelines, architectures and methods to process and retrieve these data collection. For a data control in form it is immaterial whether the data is from XML or any other data sources. We have many relational OO databases but there always the gap between the data and its processing in Objects in any modern languages.



Is LINQ the Holy Grail?
I can’t decide on that. But LINQ tries to fill the vacuum between the datasources and their successful interpretation in Objects. With LINQ, Microsoft’s intention was to provide a solution for the problem of object-relational mapping, as well as to simplify the interaction between objects and data sources. LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to access data coming from in-memory objects (LINQ to Objects), databases (LINQ to SQL), XML
documents (LINQ to XML), a file-system, or any other source.


LINQ can be used to access any type of object or datasource. The syntax remains the same. Previously we had to use different methods like ADO.Net.  XPath, IO packages etc to retrieve data ( ok still we can use these methods and in many cases I still prefer them over LINQ)


Broadly classifying we have three major categories of LINQ
  1. LINQ to Objects,
  2. LINQ to SQL,
  3. LINQ to XML


Don’t worry there are other categories like LINQ to datasets. LINQ to Entities ( with ADO.net entity framework). In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable(T) interface. In short .NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. Third parties are also free to replace the standard query operators with their own implementations that provide additional services such as remote evaluation, query translation, optimization, and so on. By adhering to the conventions of the LINQ pattern, such implementations enjoy the same language integration and tool support as the standard query operators.


Next – LINQ in action ... 

Posted: Dec 26 2009, 08:50 PM by cabhilash | with 1 comment(s)
Filed under: , ,
Difference between a constant and readonly variables/fields : (constant vs readonly)
Most of us would have encountered these questions 
  • What is the difference between constant and readonly fields?
  • When to use constant and when to use readonly fields?
  • What is the advantage/disadvantage of each?
 Constants
  • In C# you can declare a constant like this "const" is a keyword.
    public const string _constStrVar = "I am a static const str val";
  • A constant variable should have value at design time. 
  • All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".
  • Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls
Read Only  
  • Read only variables are created usually in the constructor of class. there fore it will have values before the constructor of the class exists
    class MyClass
    {
        public readonly string _strReadonly;
        public void MyClass(string strVal)        {            _strReadonly = strVal;        }           } a read only variable will have different values for each object whereas a constant variable will have only one. 

http://thetechjungle.blogspot.com/

Posted: Dec 26 2009, 08:32 PM by cabhilash | with no comments |
Filed under: , ,
using LINQ retrieve top N rows
Normally to return top N rows we use an SQL statement similar to the one belowSelect top N * from table
 but How can we achieve the same thing in DataTableI have seen many examples, using different methods. Most of the methods centered around the idea of creating new columns with automatic values increment and using them as index 
 There is better method using LINQ 
 public  DataTable GetTopNFromDataTable(int TopRowCount, DataTable dtSource)
        {

            
var dtTrec = from item in 
dtSource.AsEnumerable()
                         
select 
item;
            
var 
topN = dtTrec.Take(TopRowCount);
            
DataTable dtNew = new DataTable
();
            dtNew = dtSource.Clone();

            
foreach (DataRow drrow in 
topN.ToArray())
            {

                dtNew.ImportRow(drrow);
            }

            
return 
dtNew;
        }
  var dtTrec - stores the item in datatable, Using the Take function of Linq the first N rows is filtered

            
var topN = dtTrec.Take(TopRowCount);
 

Now how to retrieve the rows between N1 &amp; N2, just use the skip function along with Take as shown below

  public DataTable GetTopBetweenFromDataTable(int intFrom, int intTo, DataTable dtSource)
        {
......   var topN = dtTrec.Skip(intFrom).Take(intFrom); ......} 

Viewstate error : 12031

Few days ago I was asked to look into an issue. In our application we have created dynamic grids to show data from database. This ASPX page was Ajax enabled. Moreover all the rows of the grid were in edit mode ie. the normal controls like textbox,dropdowns etc  were displayed in all the rows. This grid was Paginated. But for the past few days the paging was not working.

I executed the page and found that the page was generating an error 12031  with the following message

Sys.webForms.PageRequestManagerServerErrorException:An unknown error occurred while processing the request on the server .the status code returned from the server was:12031.

On my first round of analysis I found the issue with Viewstate. If the viewstate is large then connection is reset (ERROR_INTERNET_CONNECTION_RESET ). In local machine with less load this problem will not occur but as the load & network latency increases this error will come. Once this error is generated the general events of grid is not triggered. So advised my team to minimize the use of viewstate. It will help in to load the page faster & reduce the network traffic. I can increase the maxRequestlength value to allow more data but ideally i shouldn't increase that.

In the page tested by me a page with grid  with 372 rows generated a viewstate of 4.2 mb. you can disable viewstate using EnableViewState="false" for the individual controls and for the entire page also.

With every post back this much of data is transferred back & fro & this will result in low response time.

The developer was saving all the data into viewstate in page load and from that the data was populated to the grid.

Better solution is to retrieve only the required data from database, minimize the use of  viewstate, Viewstate can be compressed also. About all these I will update in another post.

Posted: Oct 13 2009, 12:41 PM by cabhilash | with no comments |
Filed under: ,
More Posts Next page »