Translate

Thursday, December 20, 2018

.Net Assemblies Obfuscation

As you may aware that all .Net applications are compiled to Microsoft Intermediate Language(MSIL). MSIL maintain a high level information about .net assemblies (exe or dll) such as the code structure that comprises the assembly types and members such as classes, interfaces, properties, methods, fields, etc.

Any hacker or even average person can use a free decompiler such redgate's reflector and ILSpy tools to reverse engineer the process and gain access to your code. Imagine how bad is it if  your company invest a lot of money until they ship their grand-award winning product then a competitor just within a couple of hours gain access to your full featured product code. that's sucks right?

Dotfuscator is one of most well-known and reliable obfuscation tool you can either download the free community edition with limited feature or purchase the full professional edition. it makes it difficult against reverse engineering tools to gain access to your code to bypass a license or tampering the product and resell it. as per Preemtive Solutions the creator of Dotfuscator

How does Obfuscation and Code Protection Work?

Various different techniques that complement each other are used to create a layered defense to make reverse engineering, tampering, debugging much more difficult. Some examples include:
  • Rename Obfuscation
  • String Encryption
  • Control Flow Obfuscation
  • Unused Code and Metadata Removal
  • Binary Linking/Merging
  • Dummy Code Insertion
  • Instruction Pattern Transformation
  • Opaque Predicate Insertion
  • Anti-Tamper Wrapping
  • Anti-Debug Wrapping
  • Root Check for Xamarin.Android
  • Watermarking
  • Security Alerts
  • Custom Response to Tamper or Debugging

Code Before and After Rename Obfuscation and String Encryption Only

Before .NET Obfuscation
.NET Code Before Obfuscation
After .NET Obfuscation
.NET Code After Baseline Obfuscation
Here are the documentation on how to start use the protection tools using GUI and the command line interface.



Tuesday, July 31, 2018

Organizing ASP.NET MVC Applications

Choosing the right architecture or framework when you embarking doing ASP.NET MVC app is really difficult and tedious task full of traps and tricks. Therefor early planning your MVC application architecture is vital to the success of your project.

I was really over-using union architecture  in my projects for decades already. in my opinion its a robust architecture because of the following:
  • It provides better maintainability of your code since its dividing the project into different layers therefor changing the code is much easier.
  • It provides testability of  your code since you can test each layer code with out affecting other layers.
  • Domain entities and database code are the at the core of the design and are separated from the UI .
  • The internal layers of the design are not depends on the external layers therefor any change change on the external layers will not affect the internal layers.


OA.Data

It is a class library project. It holds POCO classes along with configuration classes. It represents the Domain Entities layer of the onion architecture. These classes are used to create database tables. It’s a core and central part of the application.

using System;
 
namespace OA.Data
{
    public class BaseEntity
    {
        public Int64 Id { getset; }
        public DateTime AddedDate { getset; }
        public DateTime ModifiedDate { getset; }
        public string IPAddress { getset; }
    }

}

OA.Repo

It is a second class library project. It holds generic repository class with its interface implementation. It also holds DbContext class. The Entity Framework Code First data access approach needs to create a data access context class that inherits from the DbContext class. This project represents the Repository layer of the onion architecture.

IRepository interface:
namespace OA.Repo
{
    public interface IRepository<T> where T : BaseEntity
    {
        IEnumerable<T> GetAll();
        T Get(long id);
        void Insert(T entity);
        void Update(T entity);
        void Delete(T entity);
        void Remove(T entity);
        void SaveChanges();
    }

}

namespace OA.Repo
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly ApplicationContext context;
        private DbSet<T> entities;
        string errorMessage = string.Empty;
 
        public Repository(ApplicationContext context)
        {
            this.context = context;
            entities = context.Set<T>();
        }
        public IEnumerable<T> GetAll()
        {
            return entities.AsEnumerable();
        }
 
        public T Get(long id)
        {
            return entities.SingleOrDefault(s => s.Id == id);
        }
        public void Insert(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            entities.Add(entity);
            context.SaveChanges();
        }
 
        public void Update(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            context.SaveChanges();
        }
 
        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            entities.Remove(entity);
            context.SaveChanges();
        }
        public void Remove(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            entities.Remove(entity);           
        }
 
        public void SaveChanges()
        {
            context.SaveChanges();
        }
    }
}


OA.Service

It is a third class library project. It holds business logic and interfaces. These interfaces communicate between UI and data access logic. As it communicates via interfaces, it builds applications that are loosely coupled. This project represents the Service layer of the onion architecture.

namespace OA.Service
{
    public  interface IUserService
    {
        IEnumerable<User> GetUsers();
        User GetUser(long id);
        void InsertUser(User user);
        void UpdateUser(User user);
        void DeleteUser(long id);
    }

}

namespace OA.Service
{
    public class UserService:IUserService
    {
        private IRepository<User> userRepository;
        private IRepository<UserProfile> userProfileRepository;
 
        public UserService(IRepository<User> userRepository, IRepository<UserProfile> userProfileRepository)
        {
            this.userRepository = userRepository;
            this.userProfileRepository = userProfileRepository;
        }
 
        public IEnumerable<User> GetUsers()
        {
            return userRepository.GetAll();
        }
 
        public User GetUser(long id)
        {
            return userRepository.Get(id);
        }
 
        public void InsertUser(User user)
        {
            userRepository.Insert(user);
        }
        public void UpdateUser(User user)
        {
            userRepository.Update(user);
        }
 
        public void DeleteUser(long id)
        {           
            UserProfile userProfile = userProfileRepository.Get(id);
            userProfileRepository.Remove(userProfile);
            User user = GetUser(id);
            userRepository.Remove(user);
            userRepository.SaveChanges();
        }
    }

}

OA.Web

It is an ASP.NET Core Web application in this sample but it could be Unit Test or Web API project. It is the most external part of an application by which the end user can interact with the application. It builds loosely coupled applications with in-built dependency injection in ASP.NET Core. It represents the UI layer of the onion architecture.



Sunday, September 10, 2017

Great article on the difference between IEnumerable and IQueryable in C#

I was playing around with those two lately because it causes me a terrible confusion, this article helps me to understand the difference between the two in a very abstract way .

http://haroldrv.com/2015/02/what-is-the-difference-between-ienumerable-and-iqueryable/



Monday, March 20, 2017

Convert word document to PDF file using Microsoft.Office.Interop.Word

You can use Microsoft word Api to convert word files (.doc, .docx) to a pdf files on the fly. if you are writing an automation tool or a system that manipulate word and pdf files you can utilize this API.

Microsoft.Office.Interop.Word assembly which can be found under the windows GAC folder is very easy to use and its performance are acceptable in some scenarios, so you need to study your case carefully before deciding using the component, because its uses unmanaged resources on the OS. and it have thread safety issues.


using System;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop;

public class WordToPdfConverter {

public void Convert(string sourceWordfile, string destinationPdffile)
        {
            Application word = new Application();
            if (string.IsNullOrEmpty(sourceWordfile))
            {
                throw new ArgumentNullException("sourceWordfile", "Source word file path must be passed.");
            }
            if (string.IsNullOrEmpty(destinationPdffile))
            {
                throw new ArgumentNullException("destinationPdffile", "Desitination Pdf file must be passed.");
            }
            try
            {
                word.Documents.Open(sourceWordfile);
                word.Application.Visible = false;
                word.WindowState = WdWindowState.wdWindowStateMinimize;
                Document document = word.ActiveDocument;
                document.SaveAs(destinationPdffile, WdSaveFormat.wdFormatPDF);
            }
            catch (Exception ex)
            {

                return
                    string.Format("An error occured during the conversion process, the message : {0} and the stack trace : {1}",
                        ex.Message, ex.StackTrace);
            }
            finally
            {
                word.Documents.Close();
                word.Quit(WdSaveOptions.wdDoNotSaveChanges);
            }
          
        }

}

Tuesday, September 8, 2015

Update Existing Entity using DBContext in Entity Framework Disconnected Scenario

In this article, you will learn how to update a single entity in a disconnected scenario.
If you use Database-First approach, then create an Entity Data Model as shown in the previous chapter for SchoolDB sample database. Or, if you use Code-First or Model-First approach, then create entities and context classes. In any case, entities and context classes will look similar.

Here, we will see how to update a single Student entity (not entity graph). The following is a Student entity.
    using System;
    using System.Collections.Generic;
    
    public partial class Student
    {
        public Student()
        {
            this.Courses = new HashSet<Course>();
        }
    
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public Nullable<int> StandardId { get; set; }
        public byte[] RowVersion { get; set; }
    
        public virtual Standard Standard { get; set; }
        public virtual StudentAddress StudentAddress { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
The following is a context class.
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Core.Objects;
    using System.Linq;
    
    public partial class SchoolDBEntities : DbContext
    {
        public SchoolDBEntities()
            : base("name=SchoolDBEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            
        }
    
        public virtual DbSet<Course> Courses { get; set; }
        public virtual DbSet<Standard> Standards { get; set; }
        public virtual DbSet<Student> Students { get; set; }
        public virtual DbSet<StudentAddress> StudentAddresses { get; set; }
        public virtual DbSet<Teacher> Teachers { get; set; }
  }
 The following example shows how to update a Student entity in the disconnected scenario:
    Student stud;
    //1. Get student from DB
    using (var ctx = new SchoolDBEntities())
    {
        stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>();
    }

    //2. change student name in disconnected mode (out of ctx scope)
    if (stud != null)
    {
        stud.StudentName = "Updated Student1";
    }

    //save modified entity using new Context
    using (var dbCtx = new SchoolDBEntities())
    {
        //3. Mark entity as modified
        dbCtx.Entry(stud).State = System.Data.Entity.EntityState.Modified;     
        
        //4. call SaveChanges
        dbCtx.SaveChanges();
    }
As you see in the above code snippet, we are doing the following steps:
  1. Get the existing student from DB.
  2. Change the student name out of Context scope (disconnected mode)
  3. Pass the modified entity into the Entry method to get its DBEntityEntry object and then mark its state as Modified
  4. Call SaveChanges() method to update student information into the database.
SaveChanges will send the following update query to the database:

    exec sp_executesql N'update [dbo].[Student]
    set [StudentName] = @0, [StandardId] = @1
    where ([StudentID] = @2)',N'@0 varchar(50),
    @1 int,@2 int',@0='Updated Student1',@1=299,@2=267
In this way, we can easily update a single entity using DBContext in the disconnected mode.
DbContext.Entry method returns an instance of DBEntityEntry for a specified Entity. An instance of DbEntityEntry class providea access to information about a given entity and its state. You can change the state of an entity to Added, Updated, or Deleted.
In the next chapter you will learn how to delete a single entity in the disconnected mode.
 

 

Saturday, February 28, 2015

Using ASP.NET Routing in a Web Forms Application

This walkthrough shows how to modify an existing ASP.NET Web site to include ASP.NET routing features. At the end of this walkthrough the site will have three new Web pages. Hyperlinks in one of the new pages link to the other two pages by using routes. Because these hyperlinks use routing to create the link URLs, they do not need to be changed if the target pages change names or location.

In order to run this walkthrough, you must have the following:
  • Visual Studio 2010 or later versions.
  • An ASP.NET Web site that targets the .NET Framework version 4 or later versions. If you do not already have a Web site to work with, see Walkthrough: Creating a Basic Web Page in Visual Studio.

    Creating Routes

    Routes map URL patterns to physical files. To add routes to a Web site, you add them to the static (Shared in Visual Basic) Routes property of the RouteTable class by using the RouteCollection.MapPageRoute method.
    In the following procedure, you create a method that you will use to add the routes. You call the new method from the Application_Start handler of the Global.asax page.

    To add a method to the Global.asax file for adding routes

    1. If the Web site does not already have a Global.asax file, add one by following these steps:
      1. Right-click the Web project in Solution Explorer and then select Add New Item.
      2. Select Global Application Class and then click Add.
    2. Open the Global.asax file.
    3. After the Application directive, add an Import directive for the System.Web.Routing namespace, as shown in the following example:
    <%@ Import Namespace="System.Web.Routing" %>
    void RegisterRoutes(RouteCollection routes)
    {
    } 
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
This code passes the static (Shared in Visual Basic) Routes property of the RouteData class to RegisterRoutes.
The preceding procedure added an empty method that you can use to register routes. You will now add code to this method that adds routes to the Web site.
When you have finished this procedure, your application will accept URLs like the following:
  • http://server/application/SalesReportSummary/2009
  • http://server/application/SalesReport/en-US/2009
  • http://server/application/ExpensesRoute/
  • http://server/application/ExpensesRoute/2009/
  • http://server/application/ExpensesRoute/en-US/2009?extrafield=value
ASP.NET routing will route URLs such as these to the Sales.aspx and Expenses.aspx pages.

To add routes

In the RegisterRoutes method, add the following code:
routes.MapPageRoute("",
    "SalesReportSummary/{year}",
    "~/sales.aspx");
 
This code adds an unnamed route that has a URL pattern that contains the literal value "SalesReportSummary" and a placeholder (URL parameter) named year. It maps the route to a file that is named Sales.aspx.
In the RegisterRoutes method, add the following code:

routes.MapPageRoute("SalesRoute",
    "SalesReport/{locale}/{year}",
    "~/sales.aspx");
This code adds a route that is named SalesRoute. You are naming this route because it has the same parameter list as the route that you will create in the following step. Assigning names to these two routes enables you to differentiate them when you generate URLs for them.
In the RegisterRoutes method, add the following code:

routes.MapPageRoute("ExpensesRoute",
    "ExpenseReport/{locale}/{year}/{*extrainfo}",
    "~/expenses.aspx", true,
    new RouteValueDictionary { 
        { "locale", "US" }, 
        { "year", DateTime.Now.Year.ToString() } },
    new RouteValueDictionary { 
        { "locale", "[a-z]{2}" }, 
        { "year", @"\d{4}" } });
 
This code adds a route that is named ExpensesRoute. This route includes a catch-all parameter named extrainfo. The code sets the default value of the locale parameter to "US", and it sets the default value of the year parameter to the current year. Constraints specify that the locale parameter must consist of two alphabetic characters and the year parameter must consist of four numeric digits.

Saturday, January 25, 2014

A great video tutorials on Silverlight 4

Check out this new Silverlight 4 tutorial series by the brilliant Dan wahlin, you can direct download the course from http://tut4dl.com/livelessons-introduction-silverlight-4/ 

Have Fun!
:)