validate Image content before upload in using c#

tow years ago I face the situation where a hacker uploaded the malicious asp script to our web server by changing its extension to  .jpg  and our team had put validation on file extension, but unfortunately, the file extension was .jpg  (allowed extension), so the hacker uploaded that file    .

after this situation, we learn that just checking the file extension is not enough and not the sufficient solution so we decided to make it hard and

check the file header  and the file content, but be noticed that checking the whole file content will slow the process  ;

now in this example I will check the header and later in another example, we will check the whole content.

now  to the code :

     protected void btn_Upload(object sender, EventArgs e)
        string message = string.Empty;
        Dictionary<string, byte[]> ArrImagHeader = new Dictionary<string, byte[]> {

                  {"JPG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }},
              {"JPEG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }},
              {"PNG", new byte[] { 0x89, 0x50, 0x4E, 0x47 }},
              {"TIF", new byte[] { 0x49, 0x49, 0x2A, 0x00 }},
              {"TIFF", new byte[] { 0x49, 0x49, 0x2A, 0x00 }},
              {"GIF", new byte[] { 0x47, 0x49, 0x46, 0x38 }},
              {"BMP", new byte[] { 0x42, 0x4D }},
              {"ICO", new byte[] { 0x00, 0x00, 0x01, 0x00 }},

        byte[] header;
        if (uploadctrl.HasFile)
            // GET FILE EXTENSION
            string fileExt;
            fileExt = uploadctrl.FileName.Substring(uploadctrl.FileName.LastIndexOf('.') + 1).ToUpper();
            byte[] tmp = ArrImagHeader[fileExt];
            header = new byte[tmp.Length];
            uploadctrl.FileContent.Read(header, 0, header.Length);
            if (ComparyHeaders(tmp, header))
                message = "Valid ." + fileExt + " file.";
                message = "Invalid ." + fileExt + " file.";
            message = "Please select image file.";
    private bool ComparyHeaders(byte[] target, byte[] source)
        if (source.Length != target.Length)
            return false;
        for (int i = 0; i < target.Length; i++)
            if (target[i] != source[i])
                return false;
        return true;



whey we need to use Common Table Expressions ( CTE )?

I will introduce some concepts very briefly before discussing on Common Table Expressions and why we need to use, and that because I assume that you have a good understanding of SQL already.

When we look at a basic SQL statement; the general structure  it will look like:

WHERE GROUP BY by  < list of column >

 This list can contain zero or more tables, and when there are many tables, they can be joined using inner or outer join operators, and possibly also cross join

< list of column > This list can contain zero or more column

see below example :

select count(*) from  [Customers]                    -- 10 rows
select count(*) from  [Orders]                    -- 800 rows 
select count(*) from  [Employees], [Orders]  -- 8000 rows
In the third query, we combine the tables, without a join operator. 
The result will be all the combinations of Customers with Orders, 
which will produce  8000 rows.

:: to make this query clean and readable we can rewrite it like : 
select count(*) from Customers cross join [Orders]    -- 8000 

Of Course, This is All Just A Mental Picture, Imagine a join between 3 tables, each containing 1000 rows. The resulting virtual table would contain rows

Inner Queries :

The table list can also contain the result of another SQL statement. as the following example of this:

select count(*) 
from (select * from  [Customers]) E   -- this is useless example just to explain the  idea 
select *
from  [OrderDetails] Ordet
inner join 
    (   select top 3 [order_id]
        from  [Orders]
        order by [unitprice]   desc
     ) order
on order.order_id = Ordet.orderId

Common Table Expressions

Specifies a temporary named result set, known as a common table expression 
(CTE).This is derived from a simple query and defined within the execution 
scope of a single SELECT, INSERT, UPDATE, or DELETE statement


[ WITH  [ ,...n ] ]  

    expression_name [ ( column_name [ ,...n ] ) ]  
    ( CTE_query_definition )  

Let’s first start with another clumsy example to make the idea of CTEs more clear:

;with My_cte as
    select top 3 [order_id]
    from  [OrderDetails]
    order by [unitprice]  desc
select * from My_cte 
What this does is to create a (virtual) table called My_cte, that can be used in the following query as a normal data source. The CTE is NOT a temporary table that you can use. It is part of the  statement that it belongs to, and it is local to that statement.  So later in the script, you can’t refer to the CTE table again. Given that  the CTE is part of this statement, the optimizer will use the whole  statement to make an efficient execution plan. SQL is a declarative  language: you define WHAT you want, and the optimizer decides HOW to do  this. The CTE will not necessarily be executed as first, it will depend on  the query plan. 
    A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns
    Multiple CTE query definitions can be defined in a nonrecursive CTE. The definitions must be combined by one of these set operators: UNION ALL, UNION, INTERSECT, or EXCEPT
    A CTE can reference itself and previously defined CTEs in the same WITH clause

the following clauses cannot be used in the CTE_query_definition:

    • ORDER BY (except when a TOP clause is specified)
    • INTO
    • OPTION clause with query hints

Let’s make this example more useful:

;with My_cte as
    select top 3 [order_id]
    from  [OrderDetails]
    order by [unitprice]  desc
select order_id ,orderDate , itemID,amount ,unitprice 
from  [OrderDetails] orderdet
inner join My_cte  on orderdet.order_id= My_cte .order_id
we have split the query in 2 parts: we first calculate the 3 best orders, 
then we use the results of that to select their order details. Like this, 
we can show the intent of our query.

Conclusion : 
Common Table Expressions are one of the more advanced query mechanisms in T-SQL. They can make your queries more readable, or perform queries that would otherwise be impossible, such as outputting a hierarchical list. In this case, the real power is that a CTE can reference itself, making it possible to handle recursive structures




Implementing the Singleton Pattern in C#

Essentially, a singleton is a class which only allows a single instance of itself to be created and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance, for that This article deals only with the situation where no parameters are required.

There are various different ways of implementing the singleton pattern in C# and I will describe main four ways to implement Singleton Pattern.

First Version: Not Thread Save 

public seald class  singletomInstance {

private singletomInstance (){    }

private static  singletomInstance  _singleInstance =null  ;  

Public  staitc singletomInstance  Instance {


               if(_singleInstance ==null)  {  _singleInstance  = new  singletomInstance() ;   }

                return _singleInstance ;




Second Version: simple thread Save  :

This implementation is thread-safe. The thread takes out a lock on a shared object and then checks whether or not the instance has been created before creating the instance.

public sealed class singletomInstance
private static  singletomInstance  _singleInstance =null  ;  
private static readonly object padlock = new object();

singletomInstance ()  {    }

public static  singletomInstance  Instance
                          lock (padlock)
                                    if (_singleInstance == null)
                                                  _singleInstance new Singleton();
                                           return _singleInstance ;

Third Version: Thread Save by double checking :

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn’t work in Java. This may seem an odd thing to comment on, but it’s worth knowing if you ever need the singleton pattern in Java
  •  Without any memory barriers, it’s broken in the ECMA CLI specification too. It’s possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it’s safe, but I’d rather not rely on that stronger semantics, especially if there’s any doubt as to the safety. Making the variable Instance volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can’t agree exactly which barriers are required. I tend to try to avoid situations where experts don’t agree what’s right and what’s wrong!
  • It’s easy to get wrong. The pattern needs to be pretty much exactly as Below- any significant changes are likely to impact either performance or correctness.
  • It still doesn’t perform as well as we need

public sealed class singletomInstance 
private static singletomInstance   _singleInstance null;
private static readonly object padlock = new object();

Singleton(){    }

public static singletomInstance  Instance
if (_singleInstance == null)
lock (padlock)
if (_singleInstance == null)
_singleInstance new Singleton();
return_singleInstance ;


fourth Version: thread save without lock 

public sealed class singletomInstance   
private static readonly  singletomInstance   _singleInstance new  singletomInstance   ();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static singletomInstance   ()

private  singletomInstance   ()

public static  singletomInstance   Instance
return _singleInstance ;

As you can see, this is really is extremely simple – but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples

How To improve Entity Framework Performance

it is mandatory to know about the performance of it. These are right up to a certain point as LINQ comes with its own penalties. There are some tips and tricks that we should keep in mind while designing and query database using entity framework

Here is a list of some tips you would like to know.

1) Avoid putting all the DB Objects into One Single Entity Model

If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects

2)Disable change tracking for the entity if not needed

if you need to retrieve the data only for reading purpose then no need for object tracking. disable object tracking by using MergeOption as below

NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;

3)Use Compiled Query wherever needed

Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow for the first time but after that, it boosts the performance significantly.

The following example compiles and then invokes a query that accepts a Decimal input parameter and returns a sequence of orders where the total due is greater than or equal to $200.00:

static readonly Func<AdventureWorksEntities, Decimal, IQueryable> s_compiledQuery2 = 
    CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable>(
            (ctx, total) => from order in ctx.SalesOrderHeaders
                            where order.TotalDue >= total
                            select order);

static void CompiledQuery2()
    using (AdventureWorksEntities context = new AdventureWorksEntities())
        Decimal totalDue = 200.00M;

        IQueryable orders = s_compiledQuery2.Invoke(context, totalDue);

        foreach (SalesOrderHeader order in orders)
            Console.WriteLine("ID: {0}  Order date: {1} Total due: {2}",

4)Retrieve the only required number of records

retrieve only required no of records to improve performance. This can achieve by using Take, While and Skip methods.

4)Avoid using Views

Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities

Summary  :

this is some tips to help you improve the performance I hope you enjoy reading  this article and I hop it help you to make your query in a better way

Stored procedure vs Sql function

In SQL Server functions and stored procedure are two different types of entities and every one have its  own features and limitation , for that if we now what are the major  differences between them we can write query on efficient way

I believe that they are both different things they cannot be compared. I can say, it will be like comparing apples and oranges. Each has its own unique use .

This article briefly explain What is a Stored Procedure and what is a Function in SQL Server? It also explains the working and major differences between function and stored procedure in SQL server.


Stored Procedure

A Stored Procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a Stored Procedure and then just call the Stored Procedure to execute the SQL code

User Defined Functions

Like functions in programming languages, SQL Server User Defined Functions are routines that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set.


Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

  1. Built-in Functions :The built-in functions are facility provided by the SQL Server to perform several tasks. These functions can also used in T-SQL statements. The built-in function accesses the information from SQL Server system tables without accessing the system tables directly. The built-in functions return value either scalar or table data types.
  2. User-Defined Function : The user defined functions or subroutines performs actions like complex calculation and return results. These functions are made up of one or more T-SQL statements and can be used as to encapsulate the codes for reuse.User-defined functions are created using the Create Function Like :

CREATE FUNCTION function_name( parameter_name  type , parameter_name Type …  ) RETURNS return_data_type [ WITH [ ,..n ] ] [ AS ] BEGIN function_body
RETURN scalar_expression

Types of User Defined Functions

  1. Scalar user defined functionA Scalar user defined function can accept from 0 to many input parameters and a single value will be returned as a result. A scalar UDF can return the results in the form of int, char, and varchar etc..
  2. Inline table valued user defined function: :An inline table-valued user defined function produces data type table variables and its value can be derived from the single select statement. In this function there is no need of begin and end blocks, no need to specify the variables of the tables and not allowed duplicate column names etc.. After declaration of function we can use it as like this.

    SELECT * FROM Fn_GetCityByCountryID(285)

    3. Multi Statement table valued user defined function:This is a different type of function which may contain multiple T-SQL statements. When you want to create a multi statement table valued function then you must need to define the table structure. We can use it in the FROM clause of a T-SQL command.

    After declaration of multi statements table valued user defined function as like this.

    SELECT * FROM  Fn_GetCustomerByCity(285) SELECT * FROM Fn_GetCustomerByCity(1)

Benefits of user defined Functions 

    • They allow modular programming: You can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code.
    • They allow faster execution: Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic.
    • They can reduce network traffic: An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Limitations of User Defined Functions:

  • Unable to modify the databases states.
  • Does not contains OUTPUT INTO clause.
  • A UDF can’t support TRY.. ..CATCH and SET statements.
  • Unable to call a stored procedure (SP), but can call an extended stored procedure(ESP).
  • Can not use dynamic SQL or temp tables, while table variables may use.
  • XML clause is not allowed in user defined functions.

Types of stored Procedure 

there are several four type of stored procedures in SQL. Here I have explained broadly each of them:

  1. User-defined Stored Procedure
  2. System-defined Stored Procedure:
  3. Temporary Stored Procedure:The temporary stored procedure means that it is present in temporary session. This type of stored procedures is prefixed with a hash sign (# ). Where one sign shows that it is present in the temporary session while if it used with double hash sign, this means that the procedure is present globally.
  4. Extended Stored Procedure:Extended stored procedures exist because they allow you to do things that you cannot do with T-SQL like running a DOS command (xp_cmdshell). These stored procedures are routines resides in DLLs which are very similar to the regular stored procedures. The extended stored procedures receives the parameters and return resultant value via SQL Server’s Open Data Services API.
    • Benefits of user Stored Procedures  

      Precompiled execution: SQL Server compiles each Stored Procedure once and then re utilizes the execution plan. This results in tremendous performance boosts when Stored Procedures are called repeatedly.

    • Reduced client/server traffic: If network bandwidth is a concern in your environment then you’ll be happy to learn that Stored Procedures can reduce long SQL queries to a single line that is transmitted over the wire.
    • Efficient reuse of code and programming abstraction: Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you’ll find the development cycle requires less time.
    • Enhanced security controls: You can grant users permission to execute a Stored Procedure independently of underlying table permissions. 

      Limitations of stored procedure:

      There are also some limitations of stored procedure in SQL which are discussed below:

      • Stored procedure may or not return values.
      • A stored procedure can’t be utilized in selective statements.


​When do you use structs vs classes?

when do we use a struct versus a class? So in C#,
as well as some other object-oriented programming languages,
we have the ability to create a structure in the code or we have
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
in general, are kind of saying, well, a struct in class almost
look the same, why would I use a struct over a class or why would
I use a class over a struct?–m0lBxQYy_504984382

Scoping your Solution Explorer in Visual Studio

You may find this tip very handy and useful in case you are dealing with a large solution with several projects in Visual studio.  We don’t work across the solution / all projects together. and you need to keep focus  to one project in this solution


all what you need to do is  :

    right click the project  and click   ” Scope to This


scope this


and click on the “Back”  , “Forward” or Home button to navigate across.


scope this 3


Similarly you can scoped multiple projects




Along withScope to This” feature you can also leverage “New Solution Explorer viewto create  new instances of Solution Explorer.

With this you will have two different solution explorer as shown in below screenshot.


scope this 2


How to check whether Wi-Fi Connection is enabled on Windows phone

In this short tip I shall be explaining you the simplest way to check the WiFi connection status in Windows Phone. This is a very necessary and required feature for all the apps that use an internet connection.

public bool Checkwificonnection()
bool wificonnection =                 Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled;
if (wificonnection)
  return true;
    return false;

c# to singularize – pluralize a word using PluralizationService

in this Post, we will talk about singularize – pluralize a word in c#

first, you have to add a reference  to


using System.Data.Entity.Design ;

let’s go to code …  ^_^

static void Main()
Consol.writeLine(string.Format("this is Pluralize for apple {0}" ,Pluralize("apple") )) ; 

Consol.writeLine(string.Format("this is Singularize for cars {0}" ,Singularize ("cars") )) ;


// this method is useing PluralizationService  Pluralize methos to  Pluralize  the word 

protected string Pluralize(string tablename)
var  _Plurale= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return _Plurale.Pluralize(tablename);
protected string Singularize (string tablename)
var Singular= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return Singular.Singularize(tablename);

#MVC Models creator

MVC models Creator  

its tool  that can help developers to develop MVC application without take Care about building  models from Database  the heavy work of putting data annotation attribute like required or maximum length attribute

its easy to use  see the image

enter your server credential
seelect your databse that you need to generate classes from its tables
press on generate button
select your folder you want to save files in
proccess complete
generated class
generated resource for the class