Saturday, 2 July 2016

Validate Url Syntax with Regex

Validate Url with Regex

try below regex to validate Url syntax

/^((http(s){0,1}:\/\/){0,1}www\.|http(s){0,1}:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/

for ex.

if(/^((http(s){0,1}:\/\/){0,1}www\.|http(s){0,1}:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test('www.google.com'))
{
//Matched
}
else
{
//Not matched
}


Saturday, 30 May 2015

Stop Caching of Page from Browser in Asp.Net

if you want open page every time from server then stop browser caching.

for example after logout from application, 
back/forward button of browser may be display your confidential page,
so stop caching of these pages by writing single line in C# 
in page_load or any other method.

Response.Cache.SetNoStore();

OR

Response.CacheControl = "private, no-store";

Create Custom Configuration Config Section in Web.Config/ App.Config

Suppose i have explained example with Browser Compatibility Configuration with Custom config section.

Register Configuration Class into Config Section in Config File.

<configSections>
    <section name="BrowserConfiguration" type="Demo.Web.BrowserConfiguration, Demo" allowDefinition="Everywhere" allowLocation="true"/>
 </configSections>

Add Your Configuration below Config Section Tag into Web.Config/App.Config

<BrowserConfiguration>
    <platforms>
      <platform name="winnt">
        <browsers>
          <browser browsername="IE" version="10"></browser>
          <browser browsername="FIREFOX" version="9"></browser>
          <browser browsername="CHROME" version="25"></browser>
        </browsers>
      </platform>
      <platform name="mac">
        <browsers>
          <browser browsername="IE" version="8"></browser>
          <browser browsername="CHROME" version="20"></browser>
        </browsers>
      </platform>
      <platform name="mobile">
        <browsers>
          <browser browsername="IE" version="4"></browser>
          <browser browsername="CHROME" version="10"></browser>
        </browsers>
      </platform>
    </platforms>
  </BrowserConfiguration>

Create Class For Configuration as Below.



public class BrowserElement : ConfigurationElement
{
    [ConfigurationProperty("browsername", IsRequired = true, IsKey = true)]
    public string BrowserName
    {
        get
        {
            return this["browsername"] as string;
        }
    }


    [ConfigurationProperty("version", IsRequired = true, DefaultValue = 1.0)]
    public double Version
    {
        get
        {
            return Convert.ToDouble(this["version"]);
        }
    }
}

public class BrowserCollection : ConfigurationElementCollection
{
    public new BrowserElement this[string name]
    {
        get
        {
            if (IndexOf(name) < 0)
                return null;

            return (BrowserElement)BaseGet(name);
        }
    }

    public BrowserElement this[int index]
    {
        get
        {
            return (BrowserElement)BaseGet(index);
        }
    }


    public int IndexOf(string name)
    {
        for (int idx = 0; idx < base.Count; idx++)
        {
            if (this[idx].BrowserName.Equals(name, StringComparison.CurrentCultureIgnoreCase))
                return idx;
        }

        return -1;
    }

    public int IndexOf(BrowserElement browser)
    {
        return BaseIndexOf(browser);
    }


    public override ConfigurationElementCollectionType CollectionType
    {
        get { return ConfigurationElementCollectionType.BasicMap; }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new BrowserElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((BrowserElement)element).BrowserName;
    }

    protected override string ElementName
    {
        get { return "browser"; }
    }
}

public class PlatformElement : ConfigurationElement
{
    private string m_platform = "winnt";

    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get
        {
            return Convert.ToString(base["name"]);
        }
    }

    [ConfigurationProperty("browsers", IsDefaultCollection = false)]
    public BrowserCollection Browsers
    {
        get
        {
            return (BrowserCollection)base["browsers"];
        }
    }
}

public class PlatformCollection : ConfigurationElementCollection
{
    new public PlatformElement this[string name]
    {
        get
        {
            if (IndexOf(name) < 0)
                return null;

            return (PlatformElement)BaseGet(name);
        }
    }

    public PlatformElement this[int index]
    {
        get
        {
            return (PlatformElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }

            BaseAdd(index, value);
        }
    }


    public int IndexOf(string name)
    {
        for (int idx = 0; idx < base.Count; idx++)
        {
            if (this[idx].Name.Trim().Equals(name, StringComparison.CurrentCultureIgnoreCase))
                return idx;
        }

        return -1;
    }

    public int IndexOf(PlatformElement platform)
    {
        return BaseIndexOf(platform);
    }


    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.BasicMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new PlatformElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((PlatformElement)element).Name;
    }


    public void Add(PlatformElement platform)
    {
        BaseAdd(platform);
    }

    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);
    }

    public void Remove(PlatformElement platform)
    {
        if (BaseIndexOf(platform) >= 0)
            BaseRemove(platform.Name);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }

    protected override string ElementName
    {
        get { return "platform"; }
    }
}

public class BrowserConfiguration : ConfigurationSection
{
    private static string m_ConfigurationSectionConst = "BrowserConfiguration";

    public static BrowserConfiguration GetConfig()
    {
        return (BrowserConfiguration)ConfigurationManager.GetSection(BrowserConfiguration.m_ConfigurationSectionConst) ?? new BrowserConfiguration();
    }


    [ConfigurationCollection(typeof(PlatformCollection), AddItemName = "platform")]
    [ConfigurationProperty("platforms", IsDefaultCollection = true)]
    public PlatformCollection Platforms
    {
        get
        {
            return (PlatformCollection)this["platforms"] ?? new PlatformCollection();
        }
    }
}


To read Config Section Configuration into Code , Write below Code 



var collection = BrowserConfiguration.GetConfig();

PlatformCollection values = collection.Platforms;

int index = values.IndexOf(Request.Browser.Platform);

if (index >= 0)
{
    PlatformElement platform = values[index];

    int browserindex = platform.Browsers.IndexOf(Request.Browser.Browser);

    if (browserindex >= 0)
    {
        BrowserElement browser = platform.Browsers[browserindex];

        if (browser.Version > (Convert.ToDouble(Request.Browser.MajorVersion) + Request.Browser.MinorVersion))
        {
            Server.Transfer("BrowserCompatible.aspx", false);
        }
    }
}

Monday, 27 October 2014

How to Find Faulty Machine

How to Find Faulty Machine ?



We have 10 Machines that produce Chocolate, each weighing 100 grams.  

One of the machines, however, produces chocolate weighing 90 grams only. 

We are allowed only one weighing and need to determine which machine is faulty.

you have to find faulty machine in only once try.

Machine :  [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

Bucket    :  [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

 

 

 

Solutions:

Pick 1   Chocolate From Bucket - 1
Pick 2   Chocolate From Bucket - 2
Pick 3   Chocolate From Bucket - 3
Pick 4   Chocolate From Bucket - 4
Pick 5   Chocolate From Bucket - 5
Pick 6   Chocolate From Bucket - 6
Pick 7   Chocolate From Bucket  -7
Pick 8   Chocolate From Bucket  - 8
Pick 9   Chocolate From Bucket  - 9
Pick 10 Chocolate From Bucket  - 10      
 

If All Machine are Perfect then Weight should be

Total Weight : (1 * 100) + (2 * 100) + (3 * 100) + (4 * 100) + (5 * 100) +

(6 * 100) + (7 * 100) + (8 * 100) + (9 * 100) + (10 * 100)

= 5500

 But Here 1 Machine is Faulty so Weight will be Less then 5500.
Suppose Weight is X;
you will find faulty machine No by below equation :

 

(5500 - X) / 10

will gives you faulty machine No.


lets take an example.

If 6th Machine is Faulty then 

Weight will be:

(1 * 100) + (2 * 100) + (3 * 100) + (4 * 100) + (5 * 100) +

(6 * 90) + (7 * 100) + (8 * 100) + (9 * 100) + (10 * 100)

= 5440

then 

 

= (5500 - 5440) /10 

= 60 / 10 

= 6th Machine is faulty.


as Per this you will get faulty Machine No by Only Once
Weighing in One Try.

Saturday, 18 October 2014

SQL Server CLR Functions


 SQL Server CLR Functions
You can create a database object inside an instance of SQL Server that is programmed in an assembly created in the Microsoft .NET Framework common language runtime (CLR). Database objects that can leverage the rich programming model provided by the common language runtime include aggregate functions, functions, stored procedures, triggers, and types.
Creating a CLR function in SQL Server involves the following steps:
  • Define the function as a static method of a class in a language supported by the .NET Framework. For more information about how to program functions in the common language runtime, see CLR User-Defined Functions. Then, compile the class to build an assembly in the .NET Framework by using the appropriate language compiler.
  • Register the assembly in SQL Server by using the CREATE ASSEMBLY statement. For more information about assemblies in SQL Server, see Assemblies (Database Engine).
  • Create the function that references the registered assembly by using the CREATE FUNCTION statement.

    CLR functions can be used to access external resources such as files, network resources, Web Services, other databases (including remote instances of SQL Server). This can be achieved by using various classes in the .NET Framework, such as System.IO, System.WebServices, System.Sql, and so on. The assembly that contains such functions should at least be configured with the EXTERNAL_ACCESS permission set for this purpose. For more information, see CREATE ASSEMBLY (Transact-SQL). The SQL Client Managed Provider can be used to access remote instances of SQL Server. However, loopback connections to the originating server are not supported in CLR functions. 

  1. Create the CLR Dll for the SQL function to use, and copy it to SQL Binn
  2. Register the CLR Dll in SQL server
  3. Create a normal SQL function that uses the CLR Dll 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using Microsoft.SqlServer.Server;
   5:  using System.Data;
   6:  using System.Data.Sql;
   7:  using System.Data.SqlTypes;
   8:  using Encrypt;
   9:  
  10:  public class StoredProcedures
  11:  {
  12:  
  13:      [Microsoft.SqlServer.Server.SqlFunction()]
  14:      public static string Enc(SqlString password, SqlString encStringOut)
  15:      {
  16:          Encryption enc = new Encryption();
  17:          return enc.Encrypt(password.ToString(), encStringOut.ToString());;
  18:      }
  19:  
  20:      [Microsoft.SqlServer.Server.SqlFunction()]
  21:      public static string Dec(SqlString password, SqlString encStringOut)
  22:      {
  23:          Encryption enc = new Encryption();
  24:          return enc.Decrypt(password.ToString(), encStringOut.ToString()); ;
  25:      }
  26:  }
 
So next we need to do the SQL server work. So firstly I copied the SQLServerEncryption.Dll to the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn directory of the SQL server machine.
I also copied the Dll generated (SQLServerEncryption.Dll) to the C:\ drive on the SQL server machine, as it makes the Dll registration code that needs to be run for SQL a bit easier.
So we’ve copied to \binn and C:\ so far, so now we need to register the Dll with SQL server. So lets look at that
Firstly we need to allow CLR types in the SQL server installation. Which is either done using the following SQL

EXEC dbo.sp_configure ‘clr enabled’,1 RECONFIGURE WITH
 
Or if you have issues doing it that way use the SQL Server Surface Area 
Configuration, use the “Surface Area Configuration For Features” link, 
and then CLR integration from the presented treeview. Once this is done 
we can register the CLR Dll with SQL, as follows
 
create assembly SQLServerEncryption from ‘c:SQLServerEncryption.dll’ WITH PERMISSION_SET = SAFE
 
Now that weve done that, all thats left to do is create a normal SQL 
server function that uses the CLR Dll. Which is simply done as follows 

 

ALTER FUNCTION [dbo].[ENCRYPT](@password [nvarchar](255), @encStringOut [nvarchar](255))
RETURNS [nvarchar](255) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [SQLServerEncryption].[StoredProcedures].[Enc]
 
And that it you can now use the CLR Function as you like. For example
 
dbo.ENCRYPT(‘xxxx’,’sb_SQL’) 

How Add/Drop Extended Store Procedures

Adding an Extended Stored Procedure:

 
To add an extended stored procedure function in an extended stored procedure DLL, you must run the sp_addextendedproc system stored procedure, specifying the name of the function and the name of the DLL in which that function resides. The user executing the command has to be a SQL Server system administrator.
For example, this command registers the function xp_sample, located in xp_sample.dll, as a SQL Server extended stored procedure:

sp_addextendedproc 'xp_sample','xp_sample.dll'
 
It is a good practice to place the extended stored procedure dll in the SQL Server bin path
along with any dependent dlls. 
SQL Server uses the LoadLibrary() method to locate the dll.
 
 
Example :
 
  1. Extract or build the DLL file xp_md5.dll and place it in C:\Program Files\Microsoft SQL Server\MSSQL\Binn (or wherever appropriate). A precompiled DLL is in the Release directory of the source distribution.
  2. Create an Extended Stored Procedure called xp_md5 in the "master" database. Right-click "Extended Stored Procedures" under the master database in the Server Manager and click "New Extended Stored Procedure...". Enter xp_md5 for the "Name" and for the "Path", enter the full path to xp_md5.dll
USE master;
EXEC sp_addextendedproc 'xp_md5', 'xp_md5.dll'
 
   3. Create a user-defined function for each database in which you plan to 
use the MD5 procedure. Right-click "User Defined Functions" under the 
appropriate database(s) and click "New User Defined Function...". Enter 
the following:  

 CREATE FUNCTION [dbo].[fn_md5] (@data TEXT) 
RETURNS CHAR(32) AS
BEGIN
  DECLARE @hash CHAR(32)
  EXEC master.dbo.xp_md5 @data, -1, @hash OUTPUT
  RETURN @hash
END

 

Removing an Extended Stored Procedure:

 
sp_dropextendedproc 'xp_sample','xp_sample.dll'
 
 
How Extended Stored Procedures Work
When a client call (from ISQL, your own application) to the extended stored procedure is performed which in turn executes an extended stored procedure, the request is transmitted to the SQL Server. SQL Server then locates the DLL associated with the extended stored procedure, and loads the DLL if it is not already loaded using the LoadLibrary() method. So inherently the first call to the stored procedure will have the overhead of loading the dll. Then SQL server calls the exported extended stored procedure located in the dll, which gets an interface to the SQL Server in form of a Server Procedure. Your procedure can then read parameters passed to it and return back results if it so intends.
However if your extended stored procedure raises an exception its process is killed and you have to restart the SQL server. SQL server has to be restarted even if you intend to replace the XP dll as it may have been loaded.

Debugging an Extended Stored Procedure
To debug an extended stored procedure DLL by using Microsoft Visual C++ follow the following steps.
  1. Stop SQL Server.
  2. Copy the updated SQL server extended to SQL Server bin directory preferably.
  3. Register the SQL Server using the sp_addextendedproc system stored procedure.
  4. In the project settings output Debug category for:
    • Executable for debug session: Provide $MSSSQLSERVERPATH$\BINN\sqlservr.exe
    • Working Directory: Provide $MSSSQLSERVERPATH$\BINN
    • Program arguments: -c so that SQL server starts as an application and not as an service.
  5. You can then put your break points and debug as normal.
Note:

  1. If you plan to use MFC in the stored procedure or any other dependencies be sure that it is statically linked or the dependency dlls are also available in the $MSSSQLSERVERPATH$\BINN path.
  2. Your include directory in options must contain the SQL Development tools include and lib paths.
  3. I have tried compiling and checking whether it works on SQL Server 6.5, it does. But I doubt Microsoft supports it for version 6.5.

 

What is Extended Store Procedure ?

What Is Extended Stored Procedures ?


Extended stored procedures let you create your own external routines in a programming language such as C. The extended stored procedures appear to users as regular stored procedures and are executed in the same way. Parameters can be passed to extended stored procedures, and extended stored procedures can return results and return status.

Extended stored procedures are DLLs that an instance of SQL Server can dynamically load and run. Extended stored procedures run directly in the address space of an instance of SQL Server and are programmed by using the SQL Server Extended Stored Procedure API.

After an extended stored procedure has been written, members of the sysadmin fixed server role can register the extended stored procedure with the instance of SQL Server, and then grant permission to other users to execute the procedure. Extended stored procedures can be added only to the master database. 

An extended stored procedure is a C or C++ DLL that can be called from Transact-SQL using the same syntax as calling a Transact-SQL stored procedure. Extended stored procedures are a way to extend the capabilities of Transact-SQL to include any resources or services available to Microsoft Win32 applications. In other words you can create a Extended Stored Procedure in your custom language (VC++, VB, Delphi). These dll's can use API's provided by Open Data Services to interact, control and enhance the functionality of SQL server to provide the functionality you might require. 

When to Use Extended Store Procedures ?

Examples:

  1. Imagine you have an application that performs some processing on the basis of the some records inserted newly in a particular table. The common way that one may do the same is open a recordset connection on the table and keep polling and re-querying till a new entry is inserted. The drawback in the above example is polling, it would put a lot of burden on the table on frequently accessed tables. The Extended Stored Procedure would adopt an event based approach, where an extended stored procedure residing on the server would be triggered on a new insert and perform custom processing.
  2. Imagine you have an application that needs to perform some checks on some condition and immediately send a response mail to someone notifying of the event. The drawback in the above example is you might have a particular condition to trigger the event today and a totally different condition tomorrow. The Extended Stored Procedure would adopt an event-based approach where your custom dll could generate and manage mail, all that one would have to do is to trigger the Extended Stored Procedure in the SQL Server trigger.
  3. Implemented where there is intense string operation, thread management or iteration methods which can be complicated for T-SQL.