Tuesday, November 23, 2010

Singletone Vs Static

Point 1)
Singleton 
We can get the object of singleton and then pass to other methods.
Static Class We can not pass static class to other methods as we pass objects

Point 2) 

Singleton In future, it is easy to change the logic of of creating objects to some pooling mechanism.
Static Class 
Very difficult to implement some pooling logic in case of static class. We would need to make that class as non-static and then make all the methods non-static methods, So entire your code needs to be changed.

Point3:) 
Singleton Can Singletone class be inherited to subclass? Singleton class does not say any restriction of Inheritence. So we should be able to do this as long as subclass is also inheritence.There's nothing fundamentally wrong with subclassing a class that is intended to be a singleton. There are many reasons you might want to do it. and there are many ways to accomplish it. It depends on language you use.
Static Class 
We can not inherit Static class to another Static class in C#. Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.

Code Security - .NET Obfuscation

Do you know that .NET Compiled code can be revert back to C# and VB.NET Source code. Yes it is possible by using decompiler we can get the original source code, then what about security. We can use .NET Obfuscation using dotfuscator for source code protection ...
image
All the lanugage compilers exists nowadays are producing the byte code or intermediate code that could be understandable to thier language interpreters. Microsoft .NET compiler converts the C# and VB.NET source code to MSIL (Microsoft Intermediate Languages). Java compiler converts the Java source code to byte code called class file and.
Now intersting part is there are lots of decompilers are available in market like Reflector for .NET, Dcafe for Java, hackers can get back the source code anytime from intermediate code using these decompilers. Now how we provide security for the source code. Here is the solution using ... Obfuscation  and Obfuscation Tools like Dotfuscator.
Overview
  1. Outline
  2. Define the problem
  3. Define Obfuscation
  4. Why Obfuscate?
  5. Layout Obfuscation
  6. How are we going to do it?
  7. Alternatives
  8. Conclusion
1. Outline and 2. Define the problem
Security is becoming increasingly important in the world of software. This session will discuss the various software security mechanisms focusing on applications built with .NET or Java. Topics covered include obfuscation and encryption. This session will also discuss common security vulnerabilities and provide tips and best practices to protect our code.
How.Net code is compiled ? image
image
3. Define Obfuscation
  • Obfuscate – “to confuse”
  • Behavior preserving transformations on code that preserve function but reduce readability or understandability
    •Hide what’s required, remove the rest
    •Confuse observers, but give Runtime Environment the same delivery
    •How do we confuse the reader?
4. Why Obfuscate? •IP should be protected
•Obfuscation provides important "trade secret" level protection
•Also, obfuscating may provide more legal options, since it indicates that the IP owner has taken measures to secure the IP
Code obfuscation
  • Obfuscating Arrays
image
  • Obfuscating Class
  • Obfuscating Variables
image 
Reverse engineering extracts piece of program
Obfuscation1
Obfuscation makes reverse engineering difficult
Obfuscation2 
5. Layout Obfuscation
Remove comments, identifiers
Scramble identifiers
Limited format changes
Method overloading
getPayroll() becomes a()
makeDeposit(float amount)becomes a(float a)
sendPayment(String dest) becomes a(String a)
How do we confuse the reader?
  • Control Flow Obfuscation
       - Rearranges control flow structures to make the application's logic harder to follow.
  • Removal of Unused Members
       - Removes members that are not used from the IL.
  • String Encryption
       - Encrypts strings so that they do not appear in plain text in the IL.
  • Data obfuscation
Control Flow Obfuscation
  • Change the flow of the program
  • Break the link between the original code and the obfuscated code
  • §Must ensure doesn’t introduce any bugs
  • For example, if or while statements can be transformed into other statements that are logically equivalent but more complex appearing by using the rules of logic. An obfuscator might also insert GoTo statements and labels to turn your neat logic into "spaghetti code" to further confuse human readers.
Removal of Unused Members An obfuscator can also evaluate your application's entire source code to determine whether there are any methods that are actually unused, and if so, remove them from the obfuscated assembly. This situation can easily arise if you've developed code with a code generator or used classes from a general-purpose utility library. For example: you might have collection classes with the full range of methods that any collection should support, but only use a small fraction of those methods in your application. An obfuscator can remove the unused code, making the remaining code harder to understand and shrinking the program as a beneficial side effect.
String Encryption String constants and literal strings in your .NET source code appear unchanged in your compiled .NET assemblies. Such strings can provide valuable clues for anyone trying to reverse-engineer your code. For example, an attacker trying to break a licensing routine would first focus attention on strings having to do with licensing to locate the appropriate section of code. Obfuscators can make this more difficult by encrypting the strings in the .NET assembly. This is accomplished by inserting a decryption routine into the assembly and calling the decryption code at runtime to return the original strings.
Data obfuscation
Storage obfuscation
    -Alters how data is stored in memory
     E.g. Making local variables to global and vice versa.
Aggregation obfuscation
    -Spliting an array into several array.
.NET Obfuscator Benefits: Protects and Improves .NET Code
  • Dotfuscator Professional obfuscator significantly enhances source code security.
. NET rich intermediate language is focused on application flexibility and inherently provides significant information on how an application was written. Because of this, .NET applications are more prone to reverse-engineering attack than most previous computer programs. Dotfuscator Pro includes state-of-the-art obfuscation technology to protect .NET applications - securing the important intellectual property contained within.
  • Dotfuscator Professional decreases the size of your .NET program.
Dotfuscator analyzes your application and figures out exactly which parts of your program you're really using (down to the method level!). From there it can parse out those pieces leaving you with the smallest executable possible.
  • Dotfuscator Professional improves run-time performance.
By removing unneeded program elements and renaming identifiers to small names, Dotfuscator .NET obfuscator can actually speed up programs.
  • Dotfuscator Professional provides tamper detection and notification.
Dotfuscator's Tamper Detection and Notification service notifies your organization when one of your applications detects tampering. Tampered applications cost millions in revenue to suppliers and introduce material security and liability risks to consumers.
  • Assembly Linking
Assembly linking, sometimes called merging, is the ability to merge multiple assemblies into one or more output assemblies. This can make an application even smaller and simplify deployment scenarios. When combined with obfuscation and pruning, assembly linking provides a powerful packaging solution for .NET applications.
6. How are we going to do it?

Obfuscators used in .NET

  • Salamander .NET Obfuscator
  • Spices .NET Obfuscator
  • DotFuscator

    Salamander .NET Obfuscator
§Remotesoft's Salamander .NET Obfuscator provides both a GUI environment (Remotesoft .NET Explorer) for exploring and obfuscating .NET applications.
Salamander .NET Obfuscator operates directly on your original binary exe and dll files, without altering debug and line number information. This makes source-level debugging easy; you can just drop the obfuscated assembly in place of the original, invoke the debugger, and go into your original source code
Overall, Salamander .NET Obfuscator appears to work well and the user interface makes a good deal of data on your assemblies readily accessible.
Dotfuscator - Introduction
Dotfuscator is an obfuscator, pruner, linker, and watermarker for .NET applications. It is a key component of a Secure .NET Software Development Life Cycle Process. It adds a new level of protection and application efficiency to any .NET application.
image

7. DotFuscator How to use dotfuscator
1. To open a DotFuscator you need to start up Visual Studio .Net.
Then you will be able to start up DotFuscator Community Edition.
2. All Visual Studio Programs → Microsoft 2005 → Visual Studio Tools → Dotfuscator Community Edition
image
3. Once the “Dotfuscator Community Edition” is clicked. The Dotfuscator application will startup.
image
4. Click on “input” tab and provide the dll/exe file that we have created as input.
image
5. Once the File (dll) has been taken as input, press Ctrl+B to Build the Project. You can use File → Build for the same. The result of the build can visible in output tab.
image
7. Alternatives for Legal protection
  • License agreements – EULA
  • Copyright
  • Patents
      –Dash-O example
  • DMCA and DeCSS
  • Lots of very nasty laws coming
      –Life imprisonment, P2P attacks
8. Conclusion
  • Protecting software is as important as protecting hosts
  • Watermarking, tamper-proofing and obfuscation are important tools for protecting software
  • However, no technique can prevent all attacks
  • Goal is to increase the cost for the attacker

Sunday, November 14, 2010

Implementation Singletone Pattern in c#

 public sealed class singltone
    {
        static volatile singltone instance = null;
        static readonly object obj = new object();
        singltone()
        { }
        public static singltone Instance
        {
            get
            {
                lock (obj)
                {
                    if (instance == null)
                    {
                        instance = new singltone();
                    }
                    return instance;
                }
            }
        }
        public void write()
        {
            Console.WriteLine("HI THERE");
        }

    }


    class Program
    {
        static void Main(string[] args)
        {
           singltone.Instance.write();
        }
}

Closing connection in ADO.net

When using DataReaders, specify CommandBehavior.CloseConnection.
● Do not explicitly open a connection if you use Fill or Update for a single
operation.
● Avoid checking the State property of OleDbConnection.


Use the using statement, instead of Dispose or Close, when you are working with
a single type, and you are coding in Visual C#. Dispose is automatically called for
you when you use the using statement, even when an exception occurs.

Dispose internally calls Close. In addition, Dispose clears the connection string.


using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
. . .
} // Dispose is automatically called on the conn variable here.

Change the value of readonly field from class object

This can be done using reflection.



  public class Person
{
    private int age;
    private string sex;
    readonly private static string name;
    readonly private string job;
    static Person()
    {
        name = "initial name";
    }
    public Person()
    {
        age = 10;
        sex = "male";
        job = "none";
    }
    public int Age
    {
        get
        {
            return age;
        }
    }
    public string Job
    {
        get
        {
            return job;
        }
    }
    public static string Name
    {
        get
        {
            return name;
        }
    }
    public string Sex
    {
        get
        {
            return sex;
        }
    }
}

    class Program
    {
        static void Main(string[] args)
        {
    Person p = new Person();
    Console.WriteLine(p.Job);
    Console.WriteLine(Person.Name);
    Console.WriteLine(p.Age);
          
    Type type = p.GetType();
    FieldInfo nameField = type.GetField("name", BindingFlags.NonPublic | BindingFlags.Static);
    nameField.SetValue(null, "NewName");
    FieldInfo jobField = type.GetField("job", BindingFlags.NonPublic | BindingFlags.Instance);
    jobField.SetValue(p, "New Job");
    FieldInfo ageField = type.GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
    ageField.SetValue(p, 20);
    Console.WriteLine(p.Job);
    Console.WriteLine(Person.Name);
    Console.WriteLine(p.Age);

            Console.ReadLine();
        }
    }

Note: Don't forgot to use System.Reflection Namespace.

....................

Thursday, February 4, 2010

Show and highlight the searched Record on Top in scrollable DataGrid

This post solve the problem when we search a record from a scrollable gridview or datagrid and the search record will not on the screen till we scroll down. we have a two option either we maintain the scroll position or we put the searched row on top and highlight.
The solution  is....

I just find the row from the datatable which is bind to datagird or gridview....

and create a new row and get the record from searched row ....

and delete the row from that datatable....

and insert the new created row at 0 position of the datatable and highlight it.

here is the source code


for ( int q = 0; q < dsGetDetails.Tables[0].Rows.Count; q++)

{
    //Searh the record
    if (dsGetDetails.Tables[0].Rows[q].ItemArray[0].ToString()== txtEmpId.Text.Trim())

     {
         // Create new row
         DataRow drNew = dsGetDetails.Tables[0].NewRow();
      
       // Loop through current row and copy values to new row
       for (int x = 0; x <= dsGetDetails.Tables[0].Columns.Count - 1; x++)
         {
           drNew[x] = dsGetDetails.Tables[0].Rows[q][x];
         }
     
       // Remove existing row
      dsGetDetails.Tables[0].Rows.RemoveAt(q);

     //Insert new row
    dsGetDetails.Tables[0].Rows.InsertAt(drNew, 0);


    dgDetails.DataSource = dsGetDetails.Tables[0];
    dgDetails.DataBind();


    //Now highlight the row at position 0.
     dgDetails.Items[0].BackColor = System.Drawing.Color.FromName("Red"); 
     break;

   }
}

Friday, January 29, 2010

What is the concept of Load balancing ?,what is RADWARE? what are the uses of it?

Load balancing is a Process in which web Server Traffic is distributed on multiple servers to increase the performance of the applications. It is also useful if any one server will fail,, in this situation Application will run.

For load balancing there must be 2 or more server are employed. In case one of the servers begins to get overloaded, the requests are forwarded to another server. Load balancing brings down the service time by allowing multiple servers to handle the requests. This service time is reduced by using a load balancer to identify which server has the appropriate availability to receive the traffic.


Load balancing allows the service to continue even in the face of server down time due to server failure or server maintenance. If you are load balancing across several servers and one of the servers fails, your service will still be available to your users.
 
RADWARE- Radware is a device , solve the problem of load balancing and many more. it generally distribute the request or can say that Traffic redirections in multiple servers and provides the health monitoring and server failure detection. provide maximum bandwidth utilization also provide security threads.