Friday, June 15, 2012

Translator Extension for Chrome

Today I've published my first chrome extension called Translator. I'm so exited to say this!

Few words about this:
  • This is very simple and user-friendly extension. 
  • It uses Google's translation service(http://translate.google.com/  Thank you Google! for your great work ). 
  • It supports around 64 languages. Google is still working on it to improve the current supporting languages and add few more languages.
How to use this extension?
         Select a text on the page and click on Translator icon. That's it and you are done!

Use the dropdown list to change your preferred language. It remembers your choice for the next usage.

Translator Sidebar Icon
Currently supporting languages:
Afrikaans
Albanian
Arabic
Azerbaijani
Basque
Bengali
Belarusian
Bulgarian
Catalan
Chinese Simplified
Chinese Traditional
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Filipino
Finnish
French
Galician
Georgian
German
Greek
Gujarati
Haitian Creole
Hebrew
Hindi
Hungarian
Icelandic
Indonesian


Irish
Italian
Japanese
Kannada
Korean
Latin
Latvian
Lithuanian
Macedonian
Malay
Maltese
Norwegian
Persian
Polish
Portuguese
Romanian
Russian
Serbian
Slovak
Slovenian
Spanish
Swahili
Swedish
Tamil
Telugu
Thai
Turkish
Ukrainian
Urdu
Vietnamese
Welsh
Yiddish


Again my sincere thanks to Google for the great service.

Tuesday, June 5, 2012

Create Nested Files In Visual Studio Solution Explorer


We all are aware that visual studio solution explorer views the project files in a tree like structure. If we add a directory to the root of our project and place some files there, that files will be nested on that directory. Also, we know that this nesting capability is not only for directories. In web applications, .cs and .designer.cs file will be nested under .aspx file. If you worked with entity data model, you might have observed that model's designer.cs file is nested under the .edmx file.

Now, what if we would be able to nest our own files under our own created files. Isn't it crazy? well, not much here is how we can do it. Lets take a simple example project.

In the below screen-shot, you can observe the existing non-nested files.


Here IShape is an interface and Rectangle, Triangle, and Square are the classes derived from it. It would be helpful if we were able to see this relation in the solution explorer itself, isn't it? or it will be helpful, if we were able to browse the related files immediately. Well, we can do it by nesting the implementation files under the interface file.
  • Go to the folder on windows explorer and open your project file(.csproj) with notepad or any other text or xml editor.
  • You can see the ItemGroup under PropertyGroup. Here is mine:
  <ItemGroup>
    <Compile Include="IShape.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Rectangle.cs" />
    <Compile Include="Square.cs" />
    <Compile Include="Triangle.cs" />
  </ItemGroup>
  • Modify it like this:
  <ItemGroup>
    <Compile Include="IShape.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Rectangle.cs" >
 <DependentUpon>IShape.cs</DependentUpon>
    </Compile>
    <Compile Include="Square.cs" >
 <DependentUpon>IShape.cs</DependentUpon>
    </Compile>
    <Compile Include="Triangle.cs" >
 <DependentUpon>IShape.cs</DependentUpon>
    </Compile>
  </ItemGroup>
  1. Remove the / from compile tag of the file which you would like to nest.
  2. Wrap the parent file name with the tags <DependentUpon>, i.e <DependentUpon>ParentFileName.cs</DependentUpon> and place it under the file name which you would like to nest.
  3. Close the compile tag(</compile>) of the nested file and we are done!
  • This is the final screenshot of our solution explorer:

Note: This is not only limited for inheritance. You can do it for any files. Be careful while editing the project file. Improper edit of this file will corrupt your project from being open in visual studio.

Directory Security On Webservice with Windows Authentication


Situation/Requirement: There is one folder on the root of a webservice application which contains some htmland pdf files. These files should be able to browse only for the authenticated users.

Normal Solution: The normal solution for this is to put a config file(Web.config) in that directory with these configurations:
<configuration>
 <system.web>
  <authorization>
   <deny users="?"/>
  </authorization>
 </system.web>
</configuration>
or placing these configuration on the normal Web.config file and adding the location tag which points to the appropriate directory.  For this to work, the authentication mode should be Windows or Forms. But this works only for the file types such as .aspx, .asmx, .ashx and not for the types such as htmlpdf, txt, png etc.
As mentioned in MSDN, the reason for this is:
By default, Internet Information Services (IIS) passes requests for only certain file types to ASP.NET to service. Files with file-name extensions such as .aspx, asmx, and .ashx are already mapped to the ASP.NET ISAPI extension (Aspnet_isapi.dll).
and the solution is:
To have IIS pass other file-name extensions to ASP.NET, you must register the extensions in IIS.
My Issue: My authentication mode was windows and this solution on MSDN was solved my problem to block the unauthorized users, but I was unable to provide the access for autherized users too.

My Solution: I have created a separate httphandler for the required file types, so that I can check for the proper session for authentication.
public class HttpHandler : IHttpHandler, IRequiresSessionState
{
    public HttpHandler(){}

    public void ProcessRequest(HttpContext context)
    {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;

        if(SessionHandler.Current.UserID == 0)
            Response.Redirect("~/Default.aspx");
        else
        {
            try
            {
                if (Request.Path.EndsWith(".pdf"))
                {
                    WebClient client = new WebClient();
                    Byte[] buffer = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path));
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-length", buffer.Length.ToString());
                    Response.BinaryWrite(buffer);
                }
                else
                {
                    using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(Request.Path)))
                    {
                        Response.Write(reader.ReadToEnd());
                    }
                }
            }
            catch
            {
                Response.Redirect("~/Default.aspx");
            }
        }
    }

    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }
}
Also, to make the session handling easier I have created a class called SessionHandler:
public class SessionHandler
{
    public SessionHandler()
    {
        UserID = 0;
    }

    // Gets the current session.
    public static SessionHandler Current
    {
        get
        {
            SessionHandler session =
              (SessionHandler)HttpContext.Current.Session["UserID"];
            if (session == null)
            {
                session = new SessionHandler();
                HttpContext.Current.Session["UserID"] = session;
            }
            return session;
        }
    }

    public int UserID { get; set; }

}
Finally, I added the required file extensions on the httpHandlers section of the Web.config file.
<add verb="*" path="*.html" type="HttpHandler"/>
<add verb="*" path="*.txt" type="HttpHandler"/>
<add verb="*" path="*.pdf" type="HttpHandler"/>
Now on the Login/Authentication service, I can set the session like this:
SessionHandler.Current.UserID = objResult.Id;
and on the log-out service, I can just abandon the session.

Conclusion: On any of the case we need to map the proper file extensions on IIS, otherwise IIS will not pass the page request to ASP.NET.


RenderControl - Master Page Issue


If you are using RenderControl method of a particular control on the child page of Master-Child Page environment like:
        public static string RenderControl(Control control)
        {
            string renderedString;
            using (TextWriter writer = new StringWriter())
            {
                control.RenderControl(new HtmlTextWriter(writer));
                renderedString = writer.ToString();
            }
            return renderedString;
        }
You may get the following error:
Control 'MainContent_xxx' of type 'xxx' must be placed inside a form tag with runat=server
This is because the JIT compiler fails to find <form runat=server> tag on child page that we are using. We can easily inform the JIT that we are in server form just by overriding the VerifyRenderingInServerForm method on our child page.
public override void VerifyRenderingInServerForm(Control control)
{
    // Confirms that an HtmlForm control is rendered for the
    // specified ASP.NET server control at run time.
    // No code required here.
}
This resolves the issue.

Find a Record on DataTable


Problem:

          There are situations where we need to find some records on the DataTable. To find a record, DataTable providesFind() method(with 2 overloads). However, in order to use this method we need to set the PrimaryKey. Most of the times we use DataTable instance to store returned result of some business logic methods and we may not know the structure of the table to set PrimaryKey. For example, cosider the code:
DataTable studentsData = StudentManager.getStudentsByClassID(100);
...
...
DataTable departments = DepartmentManager.getDepartmentsByID(4);
In both of the DataTable instances studentsData and departments, we are not defining the structure of the table and there by not setting the PrimaryKey.  If you try to use the Find() method here, you will get the exception MissingPrimaryKeyException (Table doesn't have a primary key):
...
DataTable studentsData = StudentManager.getStudentsByClassID(100);
DataRow dr = studentsData.Rows.Find("Jhon"); //MissingPrimaryKeyException - Table doesn't have a primary key
...
Solution: 

          We can overcome from this limitation by making use of the extension method like this:
public static class DataRowExtensions
{
    public static DataRow FindRecord(this DataRowCollection data, string keyField, string txtToFind)
    {
        foreach (DataRow dr in data)
        {
            if (txtToFind.ToUpper() == dr[keyField].ToString().ToUpper())
                return dr;
        }
        return null;
    }
}
Now we can use FindRecord method to find a record by passing appropriate column name of the value we are passing:
DataTable StudentsData = StudentManager.getStudentsByClassID(100);
DataRow dr = StudentsData.Rows.FindRecord("ST_FirstName","Jhon");
...
...
DataTable Departments = DepartmentManager.getDepartmentsByID(4);
dr = Departments.Rows.FindRecord("DPT_Name","CS");
On any page we can use this extension method by including its namespace. So, our final code looks very simple and easily understandable.

Dealing with the large data


While dealing with the large data, normally we encounter some memory related issue, more specifically system.outofmemoryexception. I faced this problem while using the DataTable to store the data. The data I was trying to load to DataTable is 2MB and the physical memory I had was 2GB which is more than enough to load this data!(however, 25% of physical memory is consumed by other processes). Then I realized that the capacity of DataTable  to store the data is only 16,777,216 records and that is what causing the issue. Obviously, in most of the situations(more than 95%)  we need not to cache this much data. So I changed my code to use SqlDataReader directly instead of caching the data on DataTable which solved the problem.

While working with SqlDataReader, the basic things that we must know are:
HasRows property -> To know whether the rows exists.
FieldCount property -> To get Column Count(No. of Columns).
GetFieldType(int i) method->Gets the type(System.Type) of specified column index.

I have created a sample code to explain the scenario, where we may need to use SqlDataReader directly instead of DataTable. Here is a method to export data to CSV using DataTable:
        public static void ExportToCSV(DataTable table, string name)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            foreach (DataColumn column in table.Columns)
            {
                context.Response.Write(column.ColumnName.ToUpper() + ",");
            }
            context.Response.Write(Environment.NewLine);

            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    string rowValue = string.Empty;
                    if (row[i] == DBNull.Value)
                        rowValue = "";
                    else
                    {
                        if (table.Columns[i].DataType == Type.GetType("System.Boolean"))
                            rowValue = (Convert.ToBoolean(row[i]) == true) ? "Y" : "N";
                        else
                            rowValue = row[i].ToString();
                    }
                    context.Response.Write(rowValue.Replace(",", string.Empty) + ",");
                }
                context.Response.Write(Environment.NewLine);
            }

            context.Response.ContentType = "text/CSV";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".csv");
            context.Response.End();

        }
Later on, you may invoke this method by loading the data from database to DataTable like this:
        DataTable myDataTable = new DataTable();
        myDataTable.Load(SqlDataReaderInstance); //Load data from database(i.e. Load method of DataTable knows how to use SqlDataReader to read the data).
        ExportToCSV(myDataTable, "myData"); //Call the ExportToCSV method by passing DataTable instance as a parameter.
This is the place where we may get system.outofmemoryexception(if the data is too large).

Here is the ExportToCSV method by using SqlDataReader:
        public static void ExportToCSV(SqlDataReader sqldr, string name)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            if (sqldr.HasRows)
            {
                for (int i = 0; i < sqldr.FieldCount; i++)
                {
                    context.Response.Write(sqldr.GetName(i).ToUpper() + ",");
                }
                context.Response.Write(Environment.NewLine);

                while (sqldr.Read())
                {
                    for (int i = 0; i < sqldr.FieldCount; i++)
                    {
                        string rowValue = string.Empty;
                        if (sqldr[i] == DBNull.Value)
                            rowValue = "";
                        else
                        {
                            if (sqldr.GetFieldType(i) == Type.GetType("System.Boolean"))
                                rowValue = (Convert.ToBoolean(sqldr[i]) == true) ? "Y" : "N";
                            else
                                rowValue = sqldr[i].ToString();
                        }
                        context.Response.Write(rowValue.Replace(",", string.Empty) + ",");
                    }
                    context.Response.Write(Environment.NewLine);

                }
            }

            context.Response.ContentType = "text/CSV";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".csv");
            context.Response.End();
        }
We can invoke this method like this:
        ExportToCSV(SqlDataReaderInstance, "myData");
By using this method we are sure that it wont raise system.outofmemoryexception and obviously it requires very less memory as the operation is real-time. It increases the performance too, since we are avoiding the DataTable which requires additional load operation.

Very Useful Uncommon Shortcuts in Visual Studio


There are many useful shortcuts in Visual Studio(Most of them works well in SQL-Management Studio too) but its difficult for us to remember them all. However, it will be help-full if we know few of them which we may need frequently. I observed several developers using the shortcuts like Ctl + K + DCtl + K + CCtl + Shift + UCtl + Uetc...but as per my observation some of the other important shortcuts are unknown for several developers. Hence, I have planned to list out few of the useful shortcuts which I know and used frequently.
Collapse: Ctl + M, O
Used to Collapse the code to its definition. Alternatively, you can press them together(Ctl + M + O). Once you collapsed the code using this shortcut, then you can use Ctl + M, L to expand the same.

Toggle Collapse All and Expand All: Ctl + M, L
To toggle all outlines. That is Collapse all and Expand all. Alternatively, you can press them together(Ctl + M + L).

Column wise Select: Shift + Alt + Arrow keys
Using this shortcut, you can select the code column wise. Alternatively, you can use Shift + Alt + (a mouse click on the desired location).



Remove white space: Ctl + K + \
Using this shortcut, you can remove the white space by mass. The below print screen is taken from SQL Management Studio.


Line Number: Ctl + G
Used to jump to the particular line. Its very useful when you have thousands of lines and want to jump to a particular line. I have used it many times when an exception occurs(i.e to go to the line where the actual exception occurred).
If the line numbers are not enabled in your system, you can enable it by following these steps(However, its not mandatory to enable LN to use Ctl + G):
  •  Go to Tools -> Options
  • Expand Text Editor -> All Languages(or your preferred language)
  • Check the check box Line Numbers


Navigate Tabs: Ctl + Tab or Ctl + Shift + Tab
Used to navigate between opened files on Visual Studio(as well as  SQL-Management Studio).

Copy Message Box Information


Normally we are receiving some warnings, information or error messages from various softwares and we want to know more information about that. Obviously most of us will search it in Google or any other search engines. I've seen most of the people struggling to type that error or warning messages in google(i.e by going back and forth). Actually, we need not to type the message manually. We can just Copy and Paste it like any other information.
  • When the error or warning occurs, just press Ctl + C.
  • Open Notepad or any other editor and Paste it. This paste contains Title, Actual message and the button text(Ok, Cancel or something else).
  • Now copy the relevant information from there and search it in Google for more info!
Example - Error Message Screen-shot:


Pasted Error message:
---------------------------
 Microsoft SQL Server Management Studio
 ---------------------------
 Evaluation period has expired. For information on how to upgrade your evaluation software please go to http://www.microsoft.com/sql/howtobuy
 ---------------------------
 OK  
 ---------------------------

Export Data to Excel Without Using Interop


Exporting the data to Excel(Spreadsheet) is one of the frequent requirement. There are plenty of ways to do this task in c#. However, for licence issues people would like to do this task without using interop library. If you just Google about this, you will get lots of different approaches along with the sample code. Since these approaches are spread over different websites, I planned to write them together.

RenderControl
Using this approach, we can easily export the data from GridView. This will be useful when we want our exported data in the same format as in the GridView.
       public void ExportToExcel(DataTable table)
        {
            StringWriter strWriter = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=MyFileName.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";

            MyGridView.DataSource = table;
            MyGridView.DataBind();
            MyGridView.RenderControl(htmlWriter);
            Response.Write(strWriter.ToString());
            Response.Flush();
            Response.End();
        }
HTML Table
Here the sheets are treated as a html table. The advantage of this approach is  easy customization. You can customize the output using any html tags.
        public void ExportToExcel(DataTable table)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            //Begin Table
            context.Response.Write("<table><tr>");

            //Write Header
            foreach (DataColumn column in table.Columns)
            {
                context.Response.Write("<th>" + column.ColumnName + "</th>");
            }
            context.Response.Write("</tr>");

            //Write Data
            foreach (DataRow row in table.Rows)
            {
                context.Response.Write("<tr>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    context.Response.Write("<td>" + row[i].ToString().Replace(",", string.Empty) + "</td>");
                }
                context.Response.Write("</tr>");
            }

            //End Table
            context.Response.Write("</table>");

            context.Response.ContentType = "application/ms-excel";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls");
            context.Response.End();
        }
OLEDB
In this approach, Excel is treated as a database and sheets as a table. The ability to write query is the key feature of this approach. This will be useful for complex operations, such as appending data to the existing file and then exporting.
        public void ExportToExcel(DataTable table, string fileName)
        {
            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            string query;
            OleDbCommand cmd;
            OleDbConnection cnn;

            try
            {
                string cnStr = GetConnectionString(fileName, Types.Excel_97_2000_2003_xls, true, true);

                cnn = new OleDbConnection(cnStr);
                cnn.Open();

                //Drop the existing sheet(first Sheet)
                query = "DROP TABLE [Sheet1$]";
                cmd = new OleDbCommand(query, cnn);
                cmd.ExecuteNonQuery();

                //Create new sheet with our requirements
                query = "CREATE TABLE [Sheet1$] (";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    query += table.Columns[i].ColumnName;
                    if (i + 1 == table.Columns.Count)
                        if (table.Columns[i].DataType == System.Type.GetType("System.Int32"))
                            query += " INT)";
                        else
                            query += " VARCHAR(255))";
                    else
                        if (table.Columns[i].DataType == System.Type.GetType("System.Int32"))
                            query += " INT,";
                        else
                            query += " VARCHAR(255),";
                }
                cmd = new OleDbCommand(query, cnn);
                cmd.ExecuteNonQuery();

                //Insert Data
                foreach (DataRow row in table.Rows)
                {
                    string values = "(";
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        if (i + 1 == table.Columns.Count)
                        {
                            if (table.Columns[i].DataType == System.Type.GetType("System.Int32"))
                                values += String.IsNullOrEmpty(row[i].ToString()) ? "0)" : row[i] + ")";
                            else
                                values += "'" + System.Security.SecurityElement.Escape(row[i].ToString()) + "')";
                        }
                        else
                        {
                            if (table.Columns[i].DataType == System.Type.GetType("System.Int32"))
                                values += String.IsNullOrEmpty(row[i].ToString()) ? "0," : row[i] + ",";
                            else
                                values += "'" + System.Security.SecurityElement.Escape(row[i].ToString()) + "',";
                        }
                    }
                    query = String.Format("Insert into [Sheet1$] VALUES {0}", values);
                    cmd = new OleDbCommand(query, cnn);
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
                return;
            }
            finally
            {
                cmd = null;
                if (cnn != null)
                    cnn.Close();
            }

            context.Response.ContentType = "application/ms-excel";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls");
            context.Response.WriteFile(fileName);
        }

        private static string GetConnectionString(string fileName, string Type, bool isHeaderExists, bool TreatIntermixedAsText)
        {
            string cnnStr;
            string provider;

            if (Type == "Excel 5.0" || Type == "Excel 8.0")
                provider = "Microsoft.Jet.OLEDB.4.0";
            else
                provider = "Microsoft.ACE.OLEDB.12.0";

            cnnStr = "Provider=" + provider +
                        ";Data Source=" + fileName +
                        ";Extended Properties=\"" + Type +
                                               ";HDR=" + (isHeaderExists ? "Yes;\"" : "No;\"");

            return cnnStr;
        }

        struct Types
        {
            /// <summary>
            /// Excel 2007 XML (*.xlsx)
            /// </summary>
            public const string Excel_2007_XML_xlsx = "Excel 12.0 Xml";

            /// <summary>
            /// Excel 2007 Binary (*.xlsb)
            /// </summary>
            public const string Excel_2007_Binary_xlsb = "Excel 12.0";

            /// <summary>
            /// Excel 2007 Macro-enabled (*.xlsm)
            /// </summary>
            public const string Excel_2007_MacroEnabled_xlsm = "Excel 12.0 Macro";

            /// <summary>
            /// Excel 97/2000/2003 (*.xls)
            /// </summary>
            public const string Excel_97_2000_2003_xls = "Excel 8.0";

            /// <summary>
            /// Excel 5.0/95 (*.xls)
            /// </summary>
            public const string Excel_95_xls = "Excel 5.0";
        }


Monday, June 4, 2012

SQL Conditional Where


Many of the times, we may come across with the situation where we need to put conditions on the WHERE clause. For example, we have the table:

IDNameJoinedDateIsActive
1NaveenNULL0
2KiranNULL1
3Peter2011-05-11 21:26:32.4230
4Jon2011-05-11 21:26:32.4231
5Harry2011-04-11 14:10:34.3870
6Nagesh2010-05-11 14:10:34.3871
7MaheshNULL1

Problem: Select the records who's joined date is less than 10 - if it is active and joined date is less than 50 - if it is inactive. But the ID's of that record should lie between 2 and 6.
When we try to write a query to solve above problem, the place where we struck is on the where clause! .
Usually,  we need not to think much here! The trick to solve this type of query is quite simple!
If we re-frame the problem......it says
  • Select the records between 2 and 6
  • Who's joined date is less than 10, if it is active
  • or who's joined date is less than 50, if it is inactive.
The question seems much simpler now! and we can easily write the query SELECT * FROM MyTable WHERE Number BETWEEN 2 AND 6 but still many of the people may struck to achieve 2nd and 3rd point.
Now just think, what you will do in coding to solve above problem....??? most probably.... you may write something like this:
If(IsActive==1)
{
    //Joined Date is Less than 10. That in SQL:
    //DATEDIFF(DAY,JoinedDate,GETDATE()) <= 10
}
Else if(IsActive==0) //or simply Else
{
    //Joined Date is Less than 50. That in SQL:
    //DATEDIFF(DAY,JoinedDate,GETDATE()) <= 50
}
We need the same effect in SQL query.  We can achieve it easily by following these procedures:
  • Place AND between the condition IsActive==1 and it's true part DATEDIFF(DAY,JoinedDate,GETDATE()) <= 10.
  • Apply the same procedure to  Else if condition too i.e. place the AND between IsActive==0and DATEDIFF(DAY,JoinedDate,GETDATE()) <= 50 
  • Now place OR between these statements.
So, the above code is logically equivalent to :
(IsActive= 1 AND DATEDIFF(DAY,JoinedDate,GETDATE()) <= 10) --if condition is ANDed with its true part.
OR --Two statements are combined with OR
(IsActive= 0 AND DATEDIFF(DAY,JoinedDate,GETDATE()) <= 50) --else if condition is ANDed with its true part.
Hence, our final query becomes:
SELECT * FROM MyTable
 WHERE Number BETWEEN 2 AND 6
  AND
 (IsActive= 1 AND DATEDIFF(DAY,JoinedDate,GETDATE()) <= 10)
  OR
 (IsActive= 0 AND DATEDIFF(DAY,JoinedDate,GETDATE()) <= 50)