Monday, March 28, 2011

Password Strength Validator

Hi Guys,

 We often need to have a password validator where the user needs to be intimated about the strength of the password which they have entered so that the user can be aware about their password.

This can be easily done with the help of Jquery.

You can email me for the sample code.

Resource: http://simplythebest.net/scripts/ajax/ajax_password_strength.html

Monday, March 21, 2011

How to change a password of a SQL Server Login??

sp_password @old='12345'@new='54321',@loginame='sa_test'
sp_password  @new='54321',@loginame='sa_test' 

How to disable the cache for back button functionality.

Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;

HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
HttpContext.Current.Response.Cache.SetNoStore();

Implement the above in the master page load event and in logout functionality.

Thursday, March 17, 2011

Concatenating the Rows

Using Sql Server 2005

CREATE TABLE FRUITS
(
[ID] INT NOT NULL,
[NAME] VARCHAR(250) NOT NULL
)

INSERT INTO FRUITS VALUES(1,'Apple')
INSERT INTO FRUITS VALUES(2,'Banana')
INSERT INTO FRUITS VALUES(3,'Orange')
INSERT INTO FRUITS VALUES(4,'Melon')
INSERT INTO FRUITS VALUES(5,'Grape')


with list as (
  select
    name as value,
    row_number() over(order by id) as num
  from
    fruits
)
,concatenations as (
  select
    value as head,
    cast('' as varchar(MAX)) as tail,
    num,
    (select top 1 name from fruits order by id desc) as terminator
  from
    list
union all
  select
    head,
    (select value from list where num = prev.num - 1) + ', ' + tail as tail,
    num - 1,
    terminator
  from
    concatenations as prev
  where
    num > 0
    and head = terminator
)
 ,
concatenated as (
  select
    max(tail + head) as items
  from
    concatenations
  where
    num = 1
)

select * from concatenated


SQL - SERVER - 2008

@ValidExtension = COALESCE((SELECT TOP 1
    (
        SELECT DT.Extension  + ', ' as [text()]
        FROM
        dbo.ProjectDocTypes PDT
        INNER JOIN
        dbo.DocumentTypes DT ON PDT.[DocTypeId] = DT.[Id]
        WHERE ClientId =  U.ClientID AND ProjectId = U.DefaultProjectId  
        ORDER BY ClientId,ProjectId ASC FOR XML PATH('')
      ) AS ValidExtension),'') 

Select @ValidExtension

Retrieving the first two scores of a student

create table marks(
StudentID int not null
,StudentName varchar(10) not null
,Subject varchar(10) not null
,Score int not null)


insert into marks values(1,'sanjeev','Math',87)
insert into marks values(1,'sanjeev','Geography',76)
insert into marks values(1,'sanjeev','History',98)
insert into marks values(1,'sanjeev','Science',85)
insert into marks values(2,'gourav','Crafts',89)
insert into marks values(2,'gourav','Science',88)
insert into marks values(2,'gourav','History',76)
insert into marks values(3,'Munish','English',87)
insert into marks values(3,'Munish','Science',76)
insert into marks values(3,'Munish','Geography',83)

In 2000
--------
select studentname, subject, score
from marks o
where score in (select top 2 score from marks i where i.studentname = o.studentname order by score desc)
order by studentname,score desc


In 2005
--------

select studentname, subject, score
from
(
select studentname, subject, score,
row_number() over (partition by studentid order by score desc) as rownum
from marks
) dt
where rownum<=2

Executing the dynamic SQL using sp_executesql

  SET @SqlParam =  N'@UsrId BIGINT,@LMBy NVARCHAR(50),@SId BIGINT,@DocId BIGINT, @ProcessId BIGINT, @RoleId BIGINT'   
    
           
  SET @Sql = N'UPDATE WFTransaction SET  UserId= @UsrId,     
  endDate=getdate(),    
  LMBy=@LMBy,    
  LMDt=getdate()    
        FROM WFTransaction AS wft    
        INNER JOIN    
        TTask AS tt    
        ON    
        wft.task_id =tt.tsk_Id            
  WHERE    
  wft.SId=@SId AND    
  wft.Doc_Id=@DocId AND     
  wft.Process_Id=@ProcessId AND     
  UPPER(tt.TSKName) IN('+@TaskName+')'   
   
     IF(UPPER(@RCode) <> 'PU')   
    SET @Sql = @Sql + ' AND wft.[Role]=@RoleId'    
    
  EXECUTE sp_executesql @Sql,@SqlParam,@UsrId=@UsrId,@LMBy=@LMBy,@SId=@SId,@DocId=@DocId,@ProcessId=@ProcessId,@RoleId=@RoleId  
   


Title Case


UPPER(LEFT(title, 1)) + LOWER(RIGHT(title, LEN(title) - 1))

Retrieving the Identity of the last inserted in a table

SELECT @POFileId=IDENT_CURRENT('dbo.POFILELOG')

CASE in Sql Server

CASE in Sql Server
------------------
Mode =
CASE dbo.TFFCJOH.FFCJOMode
     WHEN 'S' THEN 'Sea'
     WHEN 'A' THEN 'Air'        
END

Generating Row number

SELECT ROW_NUMBER() OVER (ORDER BY EMPID ASC) AS ROWID, * FROM EMPLOYEE

Checking the condition with the serial number

SELECT * FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY ALY_ID ASC) AS ROWID,
ISNULL(FCO_ID,0) AS FCO_ID,
ISNULL(FCOCode,'') AS FCOCode,
ISNULL(FCODescription,'') AS FCODescription,
ISNULL(AnalysisCOde,'') AS AnalysisCode,
ISNULL(ALYDesc,'') AS ALYDesc,
ISNULL(ALPType,'') AS ALPType,
ISNULL(ALPMinType,'') AS ALPMinType,
ISNULL(CAST(ALPMinVal AS VARCHAR(5)),'') AS ALPMinVal,
ISNULL(CAST(ALPMaxVal AS VARCHAR(5)),'') AS ALMaxVal,
ISNULL(ALPConform,'') AS ALPConform,
ISNULL(ALPDetect,'') AS ALPDetect,
ISNULL(CAST(RStatus AS VARCHAR(5)),'') AS RStatus,
ISNULL(LMBy,'') AS LMBy
FROM
TempFull) AS T
WHERE
 ROWID>=720001

Replacement for Cursor and Declaring a table variable

    DECLARE @SISubsidy
            TABLE
            (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SINumber BIGINT)


             INSERT @SISubsidy
             SELECT DISTINCT I.SINumber
             FROM
             Inserted I
             INNER JOIN
             Deleted D
             ON I.SINumber = D.SINumber
             WHERE I.Status=5 AND D.Status=4


             SELECT @MaxCount = Max(ID) FROM @SISubsidy
             Declare @Index int
             Set @Index = 1


             WHILE @Index <= @MaxCount
             BEGIN
                SELECT @SINo = SINumber FROM @SISubsidy WHERE Id=@Index   
                EXEC SI_SubsidyCreditInvoice @SINo
       
                SET @Index = @Index + 1
            END

Creating a table and moving from one table to another table

Creating a table and moving from one table to another table
------------------------------------------------------------
SELECT
ALY_ID,
FCO_ID,
AnalysisCode,
ALPType,
ALPMinType,
ALPMinVal,
ALPMaxType,
ALPMaxval,
ALPConform,
ALPDetect,
ALPPermitted,
RStatus
INTO TempFull_Bkp
FROM TempFull

Moving from one table to another when table is created
------------------------------------------------------------
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable


Moving from one table to another when table is not created
-----------------------------------------------------------
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable

IIF in Sql server

CASE WHEN dbo.INVCNT.INVCOUNT IS NULL THEN 'N' ELSE 'Y' END AS [Invoice No]

Delete, Update using Subquery

DELETE FROM dbo.TableA
FROM dbo.
TableA et
INNER JOIN
DatabaseA.dbo.
TableB AS tu
ON
tu.TeamId=et.TeamId AND tu.UserId=et.UserId
WHERE tu.IsDeleted=1



UPDATE TempFull
SET ALY_ID=cac.ALY_ID
FROM
TempFull t
INNER JOIN
CODAnalysisCode cac
ON
t.AnalysisCode=cac.ALYCode
WHERE t.ALY_ID IS NULL


Tuesday, March 15, 2011

How do I search for special characters (e.g. %) in SQL Server?

Use the Sql bracket ([ ]) or forward slash (\) when used with the special character.

Eg:

SELECT columns FROM table WHERE
    column LIKE '%[%]%' 

[or]

SELECT columns FROM table WHERE
    column LIKE '%\%%' ESCAPE '\

How to escape the square bracket itself

SELECT columns FROM table WHERE
    column LIKE '%[[]SQL Server Driver]%' 

 [or]

SELECT columns FROM table WHERE
    column LIKE '%\[SQL Server Driver]%' ESCAPE '\'

Source: 
http://sqlserver2000.databases.aspfaq.com/how-do-i-search-for-special-characters-e-g-in-sql-server.html

Monday, March 14, 2011

Type Forwarding in .NET

Type forwarding is a CLR feature that allows us to move a type from its original assembly to another assembly in such a way that there is no need to recompile the applications referring to the original assembly.

The Requirement

Suppose you have created an assembly named MyLibrary which contains a class named MyClass. Let's say, some of your applications refer to the MyLibrary whih contains MyClass. In a later phase, you decide to move MyClass from MyLibrary to a newly created assembly called MyAdvancedLibrary. If you ship a new version of MyLibrary (which now doesn't have MyClass), along with MyAdvancedLibrary, then your existing applications looking for MyClass in MyLibrary and end up with errors.

The Solution

Now, in order to run your applications without recompiling them, you can use the Type Forwarding feature of the Common Language Runtime.

In the above scenario, you need to apply TypeForwardedToAttribute to the new version of your MyLibrary, so that requests for MyClass are now forwarded to the newly created library MyAdvancedLibrary that now contains MyClass.

Steps

  1. Move the MyClass code from MyLibrary to MyAdvancedLibrary.
  2. Put TypeForwardedToAtrribute in MyLibrary for the MyClass type.
  3. // C# Example
    [assembly:TypeForwardedToAttribute(typeof(MyClass))] 
  4. Compile the newly created MyAdvancedLibrary.
  5. Add a reference of MyAdvancedLibrary into MyLibrary.
  6. Recompile MyLibrary (because MyClass used to be located in that).
Now, you can ship the new version of MyLibrary along with MyAdvancedLibrary and run your applications without a recompile!

The Limitation

The .NET Framework version 2.0 does not allow type forwarding from assemblies written in Visual Basic. However, a Visual Basic application can consume forwarded types if it uses the assemblies coded in C# or C++.


Thursday, March 10, 2011

Debugging your application attached to remote IIS.

http://www.codeproject.com/KB/aspnet/IISRemoteDebugging.aspx

http://msdn.microsoft.com/en-us/library/bt727f1t.aspx

Debugging your application attached to IIS

http://www.codeproject.com/KB/aspnet/ProcessAttache.aspx

Debugging in VS 2010 - Basics

Below is the which gives complete overlook of debugging option in VS 2010

http://www.codeproject.com/KB/cs/MasteringInDebugging.aspx

http://weblogs.asp.net/scottgu/archive/2010/08/18/debugging-tips-with-visual-studio-2010.aspx

http://www.codeproject.com/KB/debug/VS2010Debugging.aspx


Form Template

 

DatePart, DATEFIRST, @@DateFirst in Sql Server.

The weekday  in sql server is represented as

Monday = 1
Tuesday = 2
Wednesday = 3
.....
Sunday = 7

So, by default the Sunday(7) is set as the first day of the day.

So the query SELECT DATEPART(dw,'2011-03-09 20:28:36.090')

which falls on wednesday returns 4(Sunday-1.... Wednesday - 4)

you can set any day of the week to be the first day of the Week. Below is the syntax to do that

SET DATEFIRST 1 //Sets monday as the first day of the week
SELECT @@DATEFIRST   //return 1

SELECT DATEPART(dw,'2011-03-09 20:28:36.090'//return 3, since Monday is already set as default which is 1.

 
For more information on datepart 
http://msdn.microsoft.com/en-us/library/ms174420.aspx

Hope it would have helpful to you..





Wednesday, March 2, 2011

Commands

Deleting a service
sc /delete "service name"

Starting and stopping a service
net start
net stop

Run Commands
ssms  - Opens the SQL SERVER 2008.
services.msc -  Opens the services window.
shutdown - shut down windows.
acrobat - Acrobat Reader.
photoshop - Adobe Photoshop.
eventvwr.msc  - Event Viewer Manager.
firefox - firefox.
iexplore - Internet Explorer.
inetcpl.cpl - Internet Properties.
msaccess - Microsoft Access.
excel - Microsoft Excel.
mspaint - Paint.
powerpnt - Powerpoint.
MSTSC - Remote desktop.
winword - Word.
regedit32 - Windows Registry.
control schedtasks- Scheduled Tasks.
fsmgmt.msc - Shared Folder Management.
write - Wordpad.
notepad - Notepad.
regedit - Registry.
Visio  - Microsoft Visio.
Explorer - Windows Explorer.
inetmgr - IIS.
Control Panel - control.








Tuesday, March 1, 2011

How to move the LINQ - dbml file to production server.

Usually we know that the dbml acts as an interface  between the database and user interface for getting connected with the database.

We create the dbml file in our development system and itz quite obvious that the dbml file will directly point to our development database.

What if we move our application into to the production server there the database server will be pointing to the different location. So we need to manually write a code to point to the production database.

Here is the steps which you need to follow.

1. Open the LINQ project.

2. Open the Properties in that go to the file Settings.settings -> Settings.designer.cs file.


  [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=SIVA-HOME\\SQL2005;Initial Catalog=Inventory;Persist Securi" +
            "ty Info=True;User ID=sa;Password=2121212")]

        public string FreeFlockServiceConnectionString {
            get {
//this is the place which concerns us, this is value which is auto generated
//this is auto-generated by the dbml file
               // return ((string)(this["FreeFlockServiceConnectionString"]));

//create a code which point to the database from the web.config
                return ((string)(System.Configuration.ConfigurationManager.ConnectionStrings["FreeFlockServiceConnectionString"].ConnectionString));
            }
        }

3. Create a connection string tag in the web.config which is pointing to the production server database.

<add name="FreeFlockConnectionString" connectionString="Data Source=eti-sqlserver\SQL2005;Initial Catalog=FreeFlockDevSvr;UID=sa;password=courage920nw" />


Thatz cool rite!!!!