Mahmoud ElMansy: knowledge meant to be free

Problem Steps Recorder in Windows 7

This is a very handy tool if you want to record some step for documentation or send bug report to developer if you Work In a company that makes it’s own software
Or you you are making documentation for some steps you do

Here is your solution
Just type “psr” in the run .

5-11-2013 12-04-15 AM

Start recording .
5-11-2013 12-04-37 AM

Here is sample record file

Click to Dwonload

Calculate the number of days between two dates in C#

Simple way to Calculate the date the separtates two dates .

DateTime date1 = DateTime.Now.AddDays(1), date2 = DateTime.Now;
            Console.WriteLine((date1 - date2).TotalDays);
            Console.WriteLine((date1 - date2).TotalHours);
            Console.WriteLine((date1 - date2).TotalMinutes);
            Console.WriteLine((date1 - date2).TotalSeconds);
            Console.WriteLine((date1 - date2).TotalMilliseconds);
            Console.WriteLine((date1 - date2).Days);
            Console.WriteLine((date1 - date2).Hours);
            Console.WriteLine((date1 - date2).Minutes);
            Console.WriteLine((date1 - date2).Seconds);
            Console.WriteLine((date1 - date2).Milliseconds);

The difference between TotalDays and Days .
TotalDays return double the exact different .
Days return the different .

Excel MATCH Function (Compare two array of Data)

Match Function

Is a very handy Excel Function

It can be used if you have to lest of data and you want to compaire them.

Meanes if you have common data in the two list and you want to fiend the

Similara data and the position and fiend the order index of  it And to know the data that is unique.

For all that we can use MATCH  Function

Useage

First copy you data to excel sheet

And write in an empty column =MATCH(,,,)

It takes 3 Parameters

First Select The Hole first column

Second Select The Hole  Second Column

Third is an Option For Comparison

0 Exact Match

1 Less Than

-1 Greater Than

And Highlight the column and Get The difference

MatchExcell

How To Assign Data To All Models Objects And Pass Common Data To View

First let’s answer this question.
In what order are filters executed in asp.net MVC?

Answer

1) Authorization filters.
2) Action filters.
3) Response filters.
4) Exception filters.

We will talk about Action Filters
We will find 4 override method when inherits this class “System.Web.Mvc.ActionFilterAttribute” and there order on execution is.

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

In this example we will use “OnActionExecuted
This action called after action Executed and will pass Model to view
Here is the complete code of the “ViewModelFilterAttribute.cs”

  public class ViewModelFilterAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        //this is a sample property that i can pass to this class
        public string Controller
        {
            get;
            set;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
       
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Debug.WriteLine("Inside OnActionExecuted");
            // disable caching for this request
            filterContext.HttpContext.Response.Cache.SetNoServerCaching();
            filterContext.HttpContext.Response.Cache.SetNoStore();
            bool isAuthorized = filterContext.HttpContext.User.Identity.IsAuthenticated;
           
            if (isAuthorized)
            {
                if (filterContext.RouteData.Values["controller"] != null &&
                    filterContext.RouteData.Values["action"] != null &&
                    filterContext.RouteData.Values["controller"].ToString().Trim().Length > 0 &&
                    filterContext.RouteData.Values["action"].ToString().Trim().Length > 0)
                {
                    string controller = Controller;
                   
                    if (string.IsNullOrEmpty(Controller))
                        controller = filterContext.RouteData.Values["controller"].ToString();
                   
                    string action = filterContext.RouteData.Values["action"].ToString();
                    if (action.ToLower() != "delete")
                    {
                        string username = filterContext.HttpContext.User.Identity.Name;

                        //here is the main part t o get the model that is passed to view
                        var model = filterContext.Controller.ViewData.Model;

                        try
                        {
                            //here we can assign any data to the model and pass it to view
                            //note this done here only and i don't need to write it all over in every action
                            ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass = new Models.SecurityClass();

                            ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass.UserName = username;
                        }
                        catch { }
                    }
               

                }

            }
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
        }
    }

To focus on our sample The most important part is .

 //here we can assign any data to the model and pass it to view
 //note this done here only and i don't need to write it all over in every action
   ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass = new Models.SecurityClass();
    ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass.UserName = username;

First we cast our model object to “CommonModel” Class which is a class all models inherits and we assign data to this base class.

 public class CommonModel
    {
        public string ErrorMessage
        {
            get;
            set;
        }

        public SecurityClass SecurityClass
        {
            get;
            set;
        }
    }

The Model Calss

 public class AccountModel : CommonModel
    {
        public string UserName
        {
            get;
            set;
        }

        public string Email
        {
            get;
            set;
        }

        public string Password
        {
            get;
            set;
        }
    }

Conclusion
We can make base class that all models inherits and we can fill this base class with data

How to Use

 [MvcViewModelFilterAttribute.Filters.ViewModelFilter(Controller = "Account")]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
   
        public ActionResult Index()
        {
            return View();
        }
     
        public ActionResult Create()
        {
            return View(SiteViewModels.AccountViewModels.Instance.GetAccountObject(null));
        }

        public ActionResult Edit(int? userID)
        {
           
            return View(SiteViewModels.AccountViewModels.Instance. EditAction(5));
        }
        public ActionResult Details(int? userID)
        {
            return View(SiteViewModels.AccountViewModels.Instance. EditAction(5));
        }
    }

We can see that we can pass any given parameters like “Controller” to get data with or action name.
Project on the run
run the project and type “localhost:{port}/account/create/” or “localhost:{port}/account/edit/”
ViewModelFilterAttribute2

ViewModelFilterAttribute3

You can download the complete project from This link MvcViewModelFilterAttribute

Sql Server 2008 Query Designer Toolbar-Edit Data Without Update Statement

In this post i will talk about “Query Designer Toolbar“.
It is one of the coolest feature that i see on SQL.

First :  we will talk about how to show it.

showing toolBar

Second :    how to use it .

QueryDesigner2

This will show the result grid Editable (can edit the data on the flay).

QueryDesigner3

Now to start using the Cool features of the “Query Designer Toolbar“.

Let’s Get Started

1 ) We will activate the “The Show SQL Pane”

and the result as shown.

QueryDesigner4

This pane can make write my own query with any Condition i want.

QueryDesigner5

Means that i can write any query that i want and it will show in the result pane and i can edit The result data with out need to write additional update Queries 

2 ) The Change Type  “DropDownList” 

Contains a very nice tools that can speed up the developer to perform many tasks that takes a lot of time from home .

1) Insert Results…

QueryDesigner6

Just choose the table that you want to insert the data into.

QueryDesigner7

And we can the that the Insert statement Created automatic with my where condition.

QueryDesigner8

2 ) Update

QueryDesigner9

3 ) Insert Values

QueryDesigner11

4 ) Make Table

QueryDesigner12

Visual Studio 2012 JavaScript Snippet JQuery (ajax call function)

this snippet for add ajax java script function

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Keywords>
        <Keyword>JAjaxCall</Keyword>
      </Keywords>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>JAjaxCall</Title>
      <Author>ELMansy</Author>
      <Description>Ajax Call Method</Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>JAjaxCall</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>_param</ID>
          <ToolTip>_param</ToolTip>
          <Default>_param</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>Url</ID>
          <ToolTip>Url</ToolTip>
          <Default>Url</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code_ Language="javascript"><![CDATA[

$$(document).ready(function () {

function ExamCounterValue($_param$) {
   //var _data = JSON.stringify({ param: $_param$ });
   $$.ajax({
       async: false,
       type: "POST",                      
       url: "/$Url$/",
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       data: _data,
       success: function (result) {
           if (result) {
             if (result.d) {
                   return result.d;
                   
                }
           }
     
       },
       error: function (error) {
       
           document.write(error.responseText);
       }
   });
   
       try{
   } catch (err) {
       //alert(err);
   }
}
});
]]></Code_>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

You May download from here

Visual Studio 2012 JavaScript Snippet JQuery (ready function)

I will show today a simple snippet to make JQuery Document Ready function

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>SnippetFile1</Title>
      <Author>ELMansy</Author>
      <Description>
      </Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>Jready
      </Shortcut>
    </Header>
    <Snippet>
     <!--<References>
       <Reference>
         <Assembly>System.Windows.Forms.dll</Assembly>
       </Reference>
     </References>-->
      <"Code" Language="java-script">
      <![CDATA[    $$(document).ready(function () {
                  // put all your jQuery goodness in here.
                   });]]></"Code">
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Put this code in a text file name it “Jquery_Decleration.snippet”
And put it under the path of you visual studio Snippets folder
“C:\Users\UserName\Documents\Visual Studio 2012\Code Snippets\JavaScript\My Code Snippets”

Note this snippet apply for VS2012
You May download from here

Visual C# Code Snippets vs2012 (Make Function Snippet)

This is my code for the Snippet file to make a function .

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>Mansy_Func</Title>
      <Author>ELMansy</Author>
      <Description>
      </Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>Mansy_Func
      </Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>RetuenType</ID>
          <ToolTip>RetuenType</ToolTip>
          <Default>RetuenType</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>MyFunction</ID>
          <ToolTip>MyFunction</ToolTip>
          <Default>MyFunction</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code_ Language="csharp"><![CDATA[   private $RetuenType$ $MyFunction$()
       {

            throw new NotImplementedException();
       }

]]></Code_>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Visual C# Code Snippets vs2012

This is the my first post on C# Code Snippet.
Code Snippets is a very handy feature inside Visual Studio there is of course defulat code snippets like,
“try,for,foreach,do,enum” i found them very helpful.

The cool thing is that you can create your Owen Snippet.
First : where to found visual studio snippet
“%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#”

Second :  to manage Snippet inside visual studio you can do that from “Code Snippet Manager”

CodeSnippetManager

CodeSnippetManagerScreen

Now i will create my first Snippet for JQuery

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>JQuery</Title>
      <Author>ELMansy</Author>
      <Description>
      </Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>JQready
      </Shortcut>
    </Header>
    <Snippet>
     <!--<References>
       <Reference>
         <Assembly>System.Windows.Forms.dll</Assembly>
       </Reference>
     </References>-->
      <Code_ Language="javascript">
      <![CDATA[    $$(document).ready(function () {
                  // put all your jQuery goodness in here.
               });]]>
       </Code_>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

I will illustrate the XML
part 1) SnippetType :

 <SnippetType>SurroundsWith/Expansion</SnippetType>

How visual studio will write the snippet.
Part 2) Shortcut :

 <Shortcut>JQready</Shortcut>

The shortcut to write to bring the snippet.

Part 3) Code Language=”” :

  <Code Language="javascript">

Here it is “javascript”.

Part 4) you code :

<![CDATA[ //Your Code.  ]]>

T-SQL script to backup all user databases with date time backup name

This simple script to backup all user databases to specific location .

USE master;
GO
DECLARE @DATE VARCHAR(25)

SELECT @DATE= REPLACE( CONVERT(VARCHAR, GETDATE(),111),'/',':')+' '+ CONVERT(VARCHAR, GETDATE(),114);

DECLARE DB_Cursor Cursor
FOR
 
-- Get all user databases
SELECT name AS DatabaseName
FROM sys.sysdatabases
WHERE ([dbid] > 4)
 
OPEN DB_Cursor
DECLARE @DataBaseName VARCHAR(100);
DECLARE @backupPath nvarchar(100);
DECLARE @SqlStatment nvarchar(500);
DECLARE @databaseNum INT=1
 
-- backup folder and all database has a separet folder
SET @backupPath = 'c:\DataBaseBackups\'
 
Fetch NEXT FROM DB_Cursor INTO @DataBaseName
While (@@FETCH_STATUS <> -1)
 
BEGIN

set @SqlStatment =  N'
backup DATABASE ' + @DataBaseName + N' TO disk = ''' +
 @backupPath + @DataBaseName+N'
\'+@DataBaseName + N'_' +@date+ N'.bak''';
EXEC (@SqlStatment);
print convert(varchar, @databaseNum) +N'
-'+ @SqlStatment;
set @databaseNum=@databaseNum+1;
Fetch next from DB_Cursor INTO @DataBaseName
END
 
close DB_Cursor
DEALLOCATE DB_Cursor
GO