Wednesday, October 31, 2012

Creating a Plug-In Framework


Creating a Plug-In Framework

Why Do You Need a Plug-In Framework for Your Application?

People usually add plug-in support in their applications for the following reasons:
  • To extend an application's functionality without the need to re-compile and distribute it to customers.
  • To add functionality without requiring access to the original source code.
  • The business rules for the application change frequently, or new rules are added frequently.
In this article, youll build a very simple text editor, composed of only one form. All it will be able to do is to display text in a single textbox in the middle of the form. Once this application is ready, you'll create a simple plug-in and add it to the application. That plug-in will be able to read the text currently in the textbox, parse it for valid e-mail addresses, and return a string containing only those e-mails. You will then put this text inside the text box.
As you can see, there are a number of "unknowns" in this case study:
  • How do you find the plug-in from within the application?
  • How does the plug-in know what text is in the text box?
  • How do you activate this plug-in?
The answers to all of these questions will become clear as we build the solution.

Step 1. Create a Simple Text Editor

I won't bore you with the details of this. It's all in the source code download: just a simple form showing a lump of text. I'll assume from this moment that you have created this simple application.

Step 2. Create the Plug-In SDK

Now that you have an application, you will want it to be able to talk with external plug-ins. How do you make this happen?
The solution is for the application to work against a published interface, a set of public members and methods that will be implemented by all custom plug-ins. I'll call this interface IPlugin. From now on, any developer that would like to create a plug-in for your application will have to implement this interface. This interface will be located at a shared library, which both your application and any custom plug-ins will reference.
To define this interface, you need just a little data from your simple plug-in—its name, and a method that would instruct it to perform a generic action based upon the data in your application.
public interface IPlugin
{
   string Name{get;}
   void PerformAction(IPluginContext context);
}

The code is straightforward, but why send an IPluginContext interface to thePerformAction? The reason you send an interface rather than just a string is to allow more flexibility as to what object you will be able to send. Currently, this interface is very simple:
public interface IPluginContext
{
   string CurrentDocumentText{get;set;}
}

Now, all you have to do is implement this interface in one or more objects, and send this to any plug-in to receive a result. In the future this will allow you to change the string of not just a textbox, but any object you like.

Step 3. Creating Your Custom Plug-In

All you have to do now is:
  • Create a separate class library object.
  • Create a class that implements the IPlugin Interface.
  • Compile that class and place it in the same folder as the main application.
public class EmailPlugin:IPlugin
{
   public EmailPlugin()
   {
   }
   // The single point of entry to our plugin
   // Acepts an IPluginContext object
// which holds the current
   // context of the running editor.
   // It then parses the text found inside the editor
   // and changes it to reflect any
// email addresses that are found.
   public void PerformAction(IPluginContext context)
   {
      context.CurrentDocumentText=
             ParseEmails(context.CurrentDocumentText);
   }

   // The name of the plugin as it will appear
   // under the editor's "Plugins" menu
   public string Name
   {
      get
      {
         return "Email Parsing Plugin";
      }
   }

   // Parse the given string for any emails using the Regex Class
   // and return a string containing only email addresses
   private string ParseEmails(string text)
   {
      const string emailPattern= @"\w+@\w+\.\w+((\.\w+)*)?";
      MatchCollection emails =
               Regex.Matches(text,emailPattern,
               RegexOptions.IgnoreCase);
      StringBuilder emailString = new StringBuilder();
      foreach(Match email in emails)
      {
         emailString.Append(email.Value + Environment.NewLine);
      }

      return emailString.ToString();
   }
}

Step 4. Letting Your Application Know About the New Plug-In

Once you have compiled your plug-in, how do you let your application know about it?
The solution is simple:
  • Create an application configuration file.
  • Create a section in the config file that lists all the available plug-ins.
  • Create a parser for this config section.
To complete step one, just add an XML file to the main application.
Tip   Name this file App.Config. This way, every time you build your application, Microsoft® Visual Studio .NET will automatically copy this file into the build output folder and rename it to <yourApp>.Config ,saving you the hassle.
Now, the plug-in developer should be able to easily add an entry in the config file to publish each plug-in he creates. Here's how the config file should look:
<configuration>
<configSections>
      <section name="plugins"
            type="Royo.PluggableApp.PluginSectionHandler, PluggableApp"
            />
</configSections>
   <plugins>
      <plugin type="Royo.Plugins.Custom.EmailPlugin, CustomPlugin" />
   </plugins>
</configuration>

Notice the configSections Tag. This tells the application configuration settings that you have a plug-ins section in this config file, and that you have a parser for this section. This parser resides in the classRoyo.PluggableApp.PluginSectionHandler, which is in an assembly namedPluggableApp. I'll show you the code for this class below.
Next, you have the plug-ins section of the config file, which lists, for every plug-in, the class name and the assembly name in which it resides. You will use this information when you instantiate the plug-in, later on.
Once the config file is done, you have finished one end of the circle. The plug-in is ready to rock, and has published itself to all the necessary channels. All you have to do now is to enable your application to read in this information, and instantiate the published plug-ins according to this information.

Step 5. Parse the Config File Using IConfigurationSectionHandler


In order to parse out the plug-ins found within the config file of the application, the framework provides a very simple mechanism enabling you to register a specific class as a handler for a specific portion in your config file. You must have a handler for any portion in the file that is not automatically parsed by the framework; otherwise you will get a ConfigurationException thrown.
In order to provide the class that parses the plug-ins section, all you need to do is to implement the System.Configuration.IConfigurationSectionHandlerinterface. The interface itself is very simple:
public interface IConfigurationSectionHandler
{
   public object Create(object parent, object configContext, System.Xml.XmlNode section);
}

All you have to do is override the Create method in your custom class, and parse the XML node that is provided to you. This XML node, in this case, will be the "Plugins" XML node. Once you have that, you have all the information needed to instantiate the plug-ins for your application.
Your custom class must provide a default constructor, since it is instantiated automatically by the framework at run time, and then the Create method is called on it. Here's the code for the PluginSectionHandler class:
public class PluginSectionHandler:IConfigurationSectionHandler
{
   public PluginSectionHandler()
   {
   }
   // Iterate through all the child nodes
   //   of the XMLNode that was passed in and create instances
   //   of the specified Types by reading the attribite values of the nodes
   //   we use a try/Catch here because some of the nodes
   //   might contain an invalid reference to a plugin type
   public object Create(object parent,
         object configContext,
         System.Xml.XmlNode section)
   {
      PluginCollection plugins = new PluginCollection();
      foreach(XmlNode node in section.ChildNodes)
      {
         //Code goes here to instantiate
         //and invoke the plugins
         .
         .
         .
      }
      return plugins;
   }
}

As you can see in the config file mentioned earlier, you provide the data the framework needs in order to handle the plug-ins section using the configSection tag prior to the actual plug-ins tags.
<configuration>
<configSections>
   <section name="plugins"
      type="Royo.PluggableApp.PluginSectionHandler, PluggableApp"
   />
</configSections>
.
.
.
Notice how to specify the class. The string is composed of two sections: the full name of the class (including encapsulating namespaces), comma, the name of the assembly in which this class is located. This is all the framework needs to instantiate a class, and unsurprisingly, this is exactly the information required for any plug-ins to register for your application.

Instantiating and Invoking the Plug-Ins

Okay, so how would you actually instantiate an instance of a plug-in given the following string?
String ClassName = "Royo.Plugins.MyCustomPlugin, MyCustomPlugin"
IPlugin plugin =  (IPlugin )Activator.CreateInstance(Type.GetType(ClassName));

What's happening here is this: Since your application does not make a direct reference to the assembly of the custom plug-in, you use theSystem.Activator class. Activator is a special class able to create instances of an object given any number of specific parameters. It can even create instances of objects and return them. If you have ever coded in ASP or Microsoft® Visual Basic®, you might remember the CreateObject() function that was used to instantiate and return objects based on the CLSID of a class.Activator operates on the same idea, yet uses different arguments, and returns a System.Object instance, not a variant.
In this call to Activator, you pass in as a parameter the Type that you want to instantiate. Use the Type.GetType() method to return an instance of a Type that matches the Type of the plug-in. Notice that the Type.GetType() method accepts as a parameter exactly the string that was put inside the plug-ins tag, which describes the name of the class and the assembly it resides in.
Once you have an instance of the plug-in, cast it to an IPlugin interface, and put it inside your plug-in object. A Try-Catch block must be put on this line, since you cannot be sure that the plug-in described there actually exists, or does in fact support the IPlugin interface you need.
Once you have the instance of the plug-in, add it to the ArrayList of your application plug-ins, and move on to the next XML node.
Here's the code from the application:
public object Create(object parent,
    object configContext,
    System.Xml.XmlNode section)
{
   //Derived from CollectionBase
   PluginCollection plugins = new PluginCollection();
   foreach(XmlNode node in section.ChildNodes)
   {
      try
      {
         //Use the Activator class's 'CreateInstance' method
         //to try and create an instance of the plugin by
         //passing in the type name specified in the attribute value
         object plugObject =
                   Activator.CreateInstance(Type.GetType(node.Attributes["type"].Value));

         //Cast this to an IPlugin interface and add to the collection
         IPlugin plugin = (IPlugin)plugObject;
         plugins.Add(plugin);
      }
      catch(Exception e)
      {
         //Catch any exceptions
         //but continue iterating for more plugins
      }
   }
   return plugins;
}

Invoking the Plug-ins

After all this is done, you can now use the plug-ins. One more thing is missing, though. Remember that IPlugin.PerformAction() requires an argument of type IPluginContext, which holds all the necessary data for the plug-in to do its work. You'll implement a simple class that implements this interface, which you send to the PerformAction() method whenever you call a plug-in. Here's the code for the class:
public interface IPluginContext
{
   string CurrentDocumentText{get;set;}
}

public class EditorContext:IPluginContext
{
   private string m_CurrentText= string.Empty;
   public EditorContext(string CurrentEditorText)
   {
      m_CurrentText = CurrentEditorText;
   }

   public string CurrentDocumentText
   {
get{return m_CurrentText;}
      set{m_CurrentText = value;}
   }
}

Once this class is ready, you can just perform an action on the current editor text like so:

private void ExecutePlugin(IPlugin plugin)
{
   //create a context object to pass to the plugin
   EditorContext context = new EditorContext(txtText.Text);
  
   //The plugin Changes the Text property of the context
   plugin.PerformAction(context);
   txtText.Text= context.CurrentDocumentText;
   }
}

Summary

You can see that it's pretty simple to support plug-ins in your applications. You just:
  • Create a shared interfaces library.
  • Create custom plug-ins implementing the custom interfaces.
  • Create context arguments to pass to the plug-ins.
  • Create a section in your config file to hold plug-in names.
  • Instantiate plug-ins using an IConfigurationSectionHandlerimplementer class.
  • Call your plug-ins.
  • Go home and spend some quality time away from your computer.

Reference:



Anti-Cross Site Scripting (Anti XSS) Library

Microsoft Anti XSS Library :


AntiXSS helps you to protect your current applications from cross-site scripting attacks, at the same time helping you to protect your legacy application with its Security Runtime Engine. Working with customer and partner feedback, AntiXSS incorporates radically and innovatively rethought features, offering you a newer, more powerful weapon against the often employed cross-site scripting (XSS) attack. AntiXSS gives you:

Improved Performance. AntiXSS has been completely rewritten with performance in mind, and yet retains the fundamental protection from XSS attacks that you have come to rely on for your applications.
Secure Globalization. The web is a global market place, and cross-site scripting is a global issue. An attack can be coded anywhere, and Anti-XSS now protects against XSS attacks coded in dozens of languages.
Standards Compliance. AntiXSS is written to comply with modern web standards. You can protect your web application without adversely affecting its UI.
A Solid Foundation for Developers

Anti-XSS is a powerful tool in the Microsoft toolbox that mitigates XSS risks. Additionally, Anti-XSS provides a consistent level of security allowing you to focus on solving business problems and not on security problems.

No matter your development experience level, its online documentation, example code, unit tests, and calling schemes make it easy for you to know how to protect your applications from XSS attacks. Additionally, a performance data sheet helps you plan your secure deployment with full knowledge of how AntiXSS will likely perform in your environment.

http://msdn.microsoft.com/en-us/security/aa973814.aspx
http://www.microsoft.com/en-us/download/details.aspx?id=28589


Using AntiXSS

Now that you've determined which scenarios require encoding, all that is left to do is add the Microsoft Anti-Cross Site Scripting Library to your project and encode the untrusted input as it is embedded in response data. After you've installed the library you need to add a reference into your project. To do this use the following steps:
  1. Right click the project in the Solution Explorer Window in Visual Studio.
  2. Select the Add Reference ... option from the context menu.
  3. Select the browse tab and select the installation directory, then add the AntiXSSLibrary.dll appropriate for the .NET framework version you are using.
If you have not changed the install directory the library will be in C:\Program Files\Microsoft Information Security\AntiXSS Library v4.2 (32bit OSes) or C:\Program Files (x86)\Microsoft Information Security\AntiXSS Library v4.2 (64bit OSes). This folder will contain 3 directories, one for each version of the .NET framework AntiXSS supports.
Once you've added the reference to the library you will need to adjust your code to use the appropriate encoder. To do this open the files which contain code that writes output then
  1. Add a using directive; using Microsoft.Security.Application;
  2. Change the code which assigns output, for example
    string Name = Request.QueryString["Name"];
    would become
    string Name = Encoder.HtmlEncode(Request.QueryString["Name"]);
Now rebuild your web application and for XSS.

Block DoS attacks easily in ASP.NET

DoS Attack started with a warning message like this :


Today i have facing a problem of the Denial of Service (DoS) attacks on my public facing anonymous web site.

My server return the error message as "Server is too busy, Try again later".

We have firewall as well, But we dont block the IP's coz its dynamic all over the world.

Please guide me how we can prevent this attack. Or is there any way to avoid this kind of attack from the sharepoint or from the code

for this problem Mads Kristensen have simple solution  :


Denial of Service (DoS) attacks are becoming a more and more common way to bring websites and servers down. They are very easy to do and pretty hard to protect against, which is why they are so popular. The only thing you can do to prevent such an attack is to block the response to the attackers. You have no control over the requests, so you have to catch the attacker as early as possible after the request has been received by the web server.
There are two challenges to blocking the attacks
  • Identify the attackers
  • Block the response only to the attackers
To catch the request as early as possible, an HttpModule is the right place. It is executed before any page or any other handler so the impact on the server can be minimized. This HttpModule monitors all requests and block requests coming from IP addresses that make many requests in a short period of time. After a while the attacking IP address gets released from blocking.
The module is a high performance and lightweight protection from DoS attacks and very easy to implement.

Implementation


Download the DosAttackModule.cs file below and put it into the App_Code folder of your website. Then add the following lines to the web.config’s <system.web> section:
< httpModules >
< add type = " DosAttackModule " name = " DosAttackModule " />
</ httpModules >

Download



#region Using

using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Timers;

#endregion

/// <summary>
/// Block the response to attacking IP addresses.
/// </summary>
public class DosAttackModule : IHttpModule
{

  #region IHttpModule Members

  void IHttpModule.Dispose()
  {
    // Nothing to dispose; 
  }

  void IHttpModule.Init(HttpApplication context)
  {
    context.BeginRequest += new EventHandler(context_BeginRequest);
  }

  #endregion

  #region Private fields

  private static Dictionary<string, short> _IpAdresses = new Dictionary<string, short>();
  private static Stack<string> _Banned = new Stack<string>();
  private static Timer _Timer = CreateTimer();
  private static Timer _BannedTimer = CreateBanningTimer();

  #endregion

  private const int BANNED_REQUESTS = 10;
  private const int REDUCTION_INTERVAL = 1000; // 1 second
  private const int RELEASE_INTERVAL = 5 * 60 * 1000; // 5 minutes

  private void context_BeginRequest(object sender, EventArgs e)
  {
    string ip = HttpContext.Current.Request.UserHostAddress;
    if (_Banned.Contains(ip))
    {
      HttpContext.Current.Response.StatusCode = 403;
      HttpContext.Current.Response.End();
    }

    CheckIpAddress(ip);
  }

  /// <summary>
  /// Checks the requesting IP address in the collection
  /// and bannes the IP if required.
  /// </summary>
  private static void CheckIpAddress(string ip)
  {
    if (!_IpAdresses.ContainsKey(ip))
    {
      _IpAdresses[ip] = 1;
    }
    else if (_IpAdresses[ip] == BANNED_REQUESTS)
    {
      _Banned.Push(ip);
      _IpAdresses.Remove(ip);
    }
    else
    {
      _IpAdresses[ip]++;
    }
  }

  #region Timers

  /// <summary>
  /// Creates the timer that substract a request
  /// from the _IpAddress dictionary.
  /// </summary>
  private static Timer CreateTimer()
  {
    Timer timer = GetTimer(REDUCTION_INTERVAL);
    timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
    return timer;
  }

  /// <summary>
  /// Creates the timer that removes 1 banned IP address
  /// everytime the timer is elapsed.
  /// </summary>
  /// <returns></returns>
  private static Timer CreateBanningTimer()
  {
    Timer timer = GetTimer(RELEASE_INTERVAL);
    timer.Elapsed += delegate { _Banned.Pop(); };
    return timer;
  }

  /// <summary>
  /// Creates a simple timer instance and starts it.
  /// </summary>
  /// <param name="interval">The interval in milliseconds.</param>
  private static Timer GetTimer(int interval)
  {
    Timer timer = new Timer();
    timer.Interval = interval;
    timer.Start();

    return timer;
  }

  /// <summary>
  /// Substracts a request from each IP address in the collection.
  /// </summary>
  private static void TimerElapsed(object sender, ElapsedEventArgs e)
  {
    foreach (string key in _IpAdresses.Keys)
    {
      _IpAdresses[key]--;
      if (_IpAdresses[key] == 0)
        _IpAdresses.Remove(key);
    }
  }

  #endregion

}

for better view you can also view this article 
http://blog.ehuna.org/2012/04/how_to_stop_a_denial_of_servic.html from EHUNA.ORG



tsql program to kill connection sleep more than 10 min

DECLARE @v_spid INT
DECLARE c_Users CURSOR
   FAST_FORWARD FOR
   SELECT SPID
   FROM master..sysprocesses (NOLOCK)
   WHERE spid>50
   AND status='sleeping'
   AND DATEDIFF(mi,last_batch,GETDATE())>=10
   AND spid<>@@spid

OPEN c_Users
FETCH NEXT FROM c_Users INTO @v_spid
WHILE (@@FETCH_STATUS=0)
BEGIN
  PRINT 'KILLing '+CONVERT(VARCHAR,@v_spid)+'...'
  EXEC('KILL '+@v_spid)
  FETCH NEXT FROM c_Users INTO @v_spid
END

CLOSE c_Users
DEALLOCATE c_Users

TSQL CHANGE SPECIFIC CHARACTERS ENTIRE OF DATABASE


SELECT REPLACE(REPLACE('variable','ي','ی'),'ك','ک');

--- OR

Set Nocount on
                Declare @t Table (Id int identity(1,1) primary key,
                                ColumnName varchar(100),TableName varchar(100),SchemaName varchar(100))

                Declare @Id int,
                                                @ColumnName varchar(100),
                                                @TableName varchar(100),
                                                @SchemaName varchar(100),
                                                @Sql nvarchar(max)

                Insert Into @t(ColumnName,TableName,SchemaName)
                Select sys.all_columns.name, sys.objects.name,sys.schemas.name
                from sys.all_columns
                                Inner Join sys.types on sys.types.user_type_id= sys.all_columns.user_type_id
                                Inner Join sys.objects on sys.objects.object_id=sys.all_columns.object_id
                                Inner Join sys.schemas on sys.schemas.schema_id=sys.objects.schema_id
                where sys.types.system_type_id in (231,239)
                                and sys.objects.type='U'

                While Exists(Select * from @t)
                Begin
                                Select Top 1 @Id=Id,@ColumnName=ColumnName,@TableName=TableName,@SchemaName=SchemaName
                                From @t

                                Print '['+@SchemaName+N'].['+@TableName+N'].['+@ColumnName+N']'

                                Set @sql=N'
                BEGIN TRY
                                Update ['+@SchemaName+N'].['+@TableName+N']
                                Set ['+@ColumnName+N']=Replace(['+@ColumnName+N'],N''ی'',N''ي'')
                                Where ['+@ColumnName+N'] Like N''%ی%''

                                Update ['+@SchemaName+N'].['+@TableName+N']
                                Set ['+@ColumnName+N']=Replace(['+@ColumnName+N'],N''ک'',N''ك'')
                                Where ['+@ColumnName+N'] Like N''%ک%''
                END TRY
                BEGIN CATCH
          Print ''Error on update ['+@SchemaName+N'].['+@TableName+N'].['+@ColumnName+N']''
                END CATCH
                                '

                                --print @sql
                                Exec (@Sql)
                                Delete @t
                                Where Id=@Id
                End