Tuesday, January 3, 2012

Replace task manager with process explorer

Process Explorer is considered to be a more advanced form of the Windows Task Manager. it shows you information about which handles and DLLs processes have opened or loaded

You also have the option to replace the traditional Task Manager by the Process Explorer software menu: Options-> Replace Task Manager

Sunday, December 25, 2011

Simple cache provider

Instead of using the if condition to take the data from the or from the db on each data function, i have created a simple function that uses delegate and generics,
the function improve your code concentration and פrevents code replication
the function has 3 arguments:
- cacheKey - the key name to use in the cache object
- getfromDbFunc - this function will call in case that the cache is empty
- param - the parameter will be send to getfromDbFunc function


public class CacheProvider
{
public T GetData<T, P>(string cacheKey,
Func<P, T> getfromDbFunc, object param) where T : class
{
T item = HttpRuntime.Cache.Get(cacheKey) as T;
P p = (P)param;
if (item == null)
{
item = getfromDbFunc(p);
HttpContext.Current.Cache.Insert(cacheKey, item, null,
DateTime.UtcNow.AddMinutes(10),
System.Web.Caching.Cache.NoSlidingExpiration);
}
return item;
}
}


Example how to use:

protected void Page_Load(object sender, EventArgs e)
{
CacheProvider cacheProvider = new CacheProvider();
int userid = 17;
var user = cacheProvider.GetData<string, int>("user_" + userid, getUser, userid);
}
public string getUser(int id)
{
//TODO: retrieve user from db
return "newuser";
}
I'll be glad to get suggestions or improvements

Tuesday, November 29, 2011

My first Windows Phone app: SelfTimer++



Hi,
I am proud to introduce you my first Windows Phone app: SelfTimer++

SelfTimer++ gives a delay between pressing the shutter release and the shutter's firing.
Once you push the button, a countdown sound is emitted.
There is no setting page, setting is on camera screen
A trial version is also available with ads
Features:
- Self timer with countdown on screen and countdown sound
- Output tone: Grayscale, Sepia, Negative
- Set up shots in sequences of 2, 3, 4 or 5 photographs
- Autofocus and Tap to focus
- Resolution settings
- Silent mode
- Last capture image view

Tuesday, November 1, 2011

How to auto generate code

I think that, at least, something like 50% of our code is very structed and simple
and can be done by an auto generated code tool and there is no need
to write this code manually,
the main advantages of using auto generated code tool are:

  1. Saves time - don't waste your time on the simple actions, waste your time on the complicated algorithm

  2. Systemic change - for example if we want to add a new field to all the entities in the system
    we can do it in a one central place instead of to change each entity
  3. better code - the code is clean and simple

  4. coding standards built in - there is no need to make code reviews, the code is structed and known to everyone


in my sample below i use MyGeneration auto generated tool
that it is a very easy to use tool

lets say that i have a Persons table in my db(see the table code below)
and i want to create c# code and sql procedures for this entity


create TABLE [dbo].[Persons](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Counter] [int] NULL,
[BirthDate] [datetime] NULL,
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
) ON [PRIMARY]

GO



Code Generated
I want to create this basic c# classes that will represent this table:

  1. PersonBase - a class that contains all the fields of person

  2. IPerson - an interface that contains all the fields of person

  3. Person - a class that containd the logic of the entity

the idea is to update the template code in the MyGeneration template
that is based on this code lines:


<%
foreach (string columnName in columns)
{
columnAlias = DnpUtils.SetCamelCase(DnpUtils.TrimSpaces(table.Columns[columnName].Alias));
columnLanguageType = table.Columns[columnName].LanguageType;
%>
private <%=columnLanguageType%> _<%=columnAlias%>;
<%
}
%>

which means that the lines in the yellow parentheses are the logic to manipulate your
auto generate code and all the other lines are the auto generated code output
in this sample i make a loop through all the columns of the table and create a
private data member in c#

you may see the output of this c# code template below:





/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************
*
*
* PersonBase - A Class Representing Persons' fields/columns
*
*
/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************/


using System;
using System.Text;
using System.Data;

namespace My.Framework.Core.Application
{
[Serializable()]
public class PersonBase : IMyObject
{
#region MyGeneration Auto-Generated Code

#region fields
private int _id;
private string _name;
private int? _counter;
private DateTime _birthDate = DateTime.MinValue;

#endregion

#region properties

public int Id
{
get { return _id; }
set { _id = value;}
}

public string Name
{
get { return _name; }
set { _name = value;}
}

public int? Counter
{
get { return _counter; }
set { _counter = value;}
}

public DateTime BirthDate
{
get { return _birthDate; }
set { _birthDate = value;}
}
#endregion

#region Constructors

public PersonBase(){}
public PersonBase(IDataReader reader)
{

this._id = (int)Convert.ChangeType(reader["ID"], typeof(int));
if (!reader.IsDBNull(reader.GetOrdinal("Name")))
{
this._name = (string)Convert.ChangeType(reader["Name"], typeof(string));
}
if (!reader.IsDBNull(reader.GetOrdinal("Counter")))
{
this._counter = (int)Convert.ChangeType(reader["Counter"], typeof(int));
}
if (!reader.IsDBNull(reader.GetOrdinal("BirthDate")))
{
this._birthDate = (DateTime)Convert.ChangeType(reader["BirthDate"], typeof(DateTime));
}
}
public PersonBase(int id, string name, int? counter, DateTime birthDate)
{
this._id = id;
this._name = name;
this._counter = counter;
this._birthDate = birthDate;
}

#endregion

#region IMyObject Members

public DateTime Created
{
get { return DateTime.MinValue; }
set { throw new NotImplementedException(); }
}

public DateTime Deleted
{
get { return DateTime.MinValue; }
set { throw new NotImplementedException(); }
}

public DateTime Updated
{
get { return DateTime.MinValue; }
set { throw new NotImplementedException(); }
}

#endregion

#endregion
}
}




/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************
*
*
* IPerson - An Interface representing Persons
*
*
/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************/


using System;
using System.Text;
using System.Data;
using My.BusinessLogic.DataAccess;
using My.Framework;
using My.Framework.Core.Application;
using My.BusinessLogic.Application;

namespace My.BusinessLogic
{
public interface IPerson
{
#region MyGeneration Auto-Generated Code

#region properties
int Id{get;set;}
string Name{get;set;}
int? Counter{get;set;}
DateTime BirthDate{get;set;}
#endregion

#endregion
}
}




/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************
*
*
* Person BL's Class Code
*
*
/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************/


using System;
using System.Text;
using System.Data;
using My.BusinessLogic.DataAccess;
using My.Framework;
using My.Framework.Core.Application;
using My.BusinessLogic.Application;

namespace My.BusinessLogic
{
[Serializable]
public class Person : PersonBase,IPerson
{
#region MyGeneration Auto-Generated Code

#region Constructors

public Person() : base()
{}
public Person(IDataReader reader) : base(reader)
{}


public Person(int id, string name, int? counter, DateTime birthDate) :
base(id, name, counter, birthDate) {}

#endregion


#region ISchemaDataObject Members

public bool Save(ISession session)
{
if (Id == -1) //Insert
{
Id = session.GetDataSource().Insert(this);
}
else //Update
{
session.GetDataSource().Update(this);
}
return true;
}

public bool Delete(ISession session)
{
throw new NotImplementedException("Delete wasn't generated, kindly implement it please.");
}

#endregion


#endregion
}
}






/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************
*
*
* SQL - Stored Procedures
*
*
/**************************************************************************************************
/**************************************************************************************************
/**************************************************************************************************

Get From the 2nd util..


and download the full template here



Sql Generated
I want to create this basic sql procedure that will represent this table:

  1. SP_Person_Insert - a procedure that insert a new person

  2. SP_Person_Update - a procedure that update an existing person

  3. SP_Person_Delete - a procedure that delete an existing person

  4. SP_GetPerson_ByID - a procedure that return the requested person

here the idea is a little bit different
the idea is to create a list of fields (for example: [Name], [Counter], [BirthDate])
and list of values (for example: @Name, @Counter, @BirthDate)
and to use it in the output of the template
i recommend you to download the full template from here
and to customize it as you wish

you may see the output of this sql procedure template below:


<%
//------------------------------------------------------------------------------
// SQL_StoredProcs.jgen
// Last Update : 2/21/2004
//
// Be sure to rename this template if you plan to customize it, MyGeneration
// Software will update this sample over time.
//------------------------------------------------------------------------------
//
// This template generates 3 stored procedures
//
// 1) [TableName]Update
// 2) [TableName]Insert
// 3) [TableName]Delete
//
// There is script in the "Interface Code" tab that pops up a dialog so you can tell this tempate
// where to save the files and what tables you want to generate stored procedures for. So, the
// logic at a very high level looks like this:
//
// For Each TableName in Select Tables
// objTable = database.Tables.Item(TableName)
// Generate the 3 stored procs for objTable
// Save file
// Next
//
// However, all of the script ends up in the Output tab and you can copy this right into
// Sql QueryAnalyzer and execute it. It's a pretty smart template, it knows to make
// Identity Columns output parameters to return them, the same holds true for computed
// Columns. It knows how to use PrimaryKeys in WHERE clauses and not to update them
// in the UpdateStored Proc, if you have a TimeStamp it will do the comparison for you and
// so on. This template alone can save you tons of time, and at anytime you can regenerate
// them as tables change.
//------------------------------------------------------------------------------
// Justin Greenwood
// MyGeneration Software
// justin.greenwood@mygenerationsoftware.com
// http://www.mygenerationsoftware.com/
//------------------------------------------------------------------------------

// collect needed data/objects and put them in local variables
var databaseName = input.Item("cmbDatabase");
var tablenames = input.Item("lstTables");
var database = MyMeta.Databases.Item(databaseName);

// Filename info
var filepath = input.item("txtPath");
if (filepath.charAt(filepath.length - 1) != '\\') filepath += "\\";

// The buffer that will hold all the output for rendering.
var buffer = "";

for (var i = 0; i < tablenames.Count; i++)
{
var tablename = tablenames.item(i);
var tableMeta = database.Tables.Item(tablename);

// Single name
var tableNameSingle = DnpUtils.SetPascalCase(DnpUtils.TrimSpaces(tableMeta.Alias));;

if (tableNameSingle.match("ies$") == "ies") // ends with
tableNameSingle = tableNameSingle.substr(0, tableNameSingle.length - 3) + "y";
else if (tableNameSingle.match("s$") == "s") // ends with
tableNameSingle = tableNameSingle.substr(0, tableNameSingle.length - 1);


// Build the filename
var filename = filepath + "sql_procs_" + tablename + ".sql"

var insertProcName = "SP_" + tableNameSingle + "_Insert";
var insertParams = "";
var insertFields = "";
var insertValues = "";
var insertAutoKeyCode = "";
var insertComputedCode = "";

var updateProcName = "SP_" + tableNameSingle + "_Update";
var updateParams = "";
var updateSet = "";
var updateWhere = "";

var deleteProcName = "SP_" + tableNameSingle + "_Delete";
var selectProcName = "SP_Get" + tableNameSingle + "_ByID";
var deleteParams = "";
var deleteWhere = "";

var paramName = "";

var hasComputedFields = false;
var hasTimestamp = false;

// Loop through all the columns of the table
for (var j = 0; j < tableMeta.Columns.Count; j++)
{
column = tableMeta.Columns.Item(j);
paramName = column.Name.split(' ').join('')

// If the datatype is not a timestamp, add it to the insert statement
if (column.DataTypeName == "timestamp")
{
hasTimestamp = true;
}
else if (!column.IsComputed)
{
if (insertParams != "")
{
insertParams += ",\r\n";
}
if (insertFields != "")
{
insertFields += ",\r\n";
insertValues += ",\r\n";
}

insertParams += "\t@" + paramName + " " + column.DataTypeNameComplete

if ((column.DataTypeName == "uniqueidentifier") && (column.IsInPrimaryKey) && (tableMeta.PrimaryKeys.Count == 1))
{
insertParams += " = NEWID() OUTPUT";
}
else if (column.IsNullable || column.IsAutoKey || column.IsComputed)
{
insertParams += " = NULL";

if (column.IsAutoKey || column.IsComputed)
{
insertParams += " OUTPUT";
}
}

if (!column.IsAutoKey && !column.IsComputed)
{
insertFields += "\t\t[" + column.Name + "]";
insertValues += "\t\t@" + paramName;
}
}

if (column.IsAutoKey)
{
insertAutoKeyCode += "\tSELECT @" + paramName + " = SCOPE_IDENTITY();\r\n";
}

if (column.IsComputed)
{
if (insertComputedCode == "")
{
hasComputedFields = true;
insertComputedCode += "\tSELECT ";
}
else
{
insertComputedCode += ", \r\n";
}
insertComputedCode += "\t\t@" & paramName & " = [" & column.Name & "]"
}

if (!column.IsComputed)
{
if (updateParams != "")
{
updateParams += ",\r\n";
}

updateParams += "\t@" + paramName + " " + column.DataTypeNameComplete;
if (column.IsNullable || column.IsComputed || column.DataTypeName == "timestamp")
{
updateParams += " = NULL";

if (column.IsComputed)
{
updateParams += " output";
}
}


if (column.IsInPrimaryKey || column.DataTypeName == "timestamp")
{
if (updateWhere != "")
{
updateWhere += " AND\r\n";
}

if (column.DataTypeName == "timestamp")
{
updateWhere += "\t\tTSEQUAL(" + column.Name + ", @" + paramName + ")";
}
else
{
updateWhere += "\t\t[" + column.Name + "] = @" + paramName;
}
}

if (!column.IsComputed && !column.IsAutoKey && column.DataTypeName != "timestamp")
{
if (updateSet != "")
{
updateSet += ",\r\n";
}

updateSet += "\t\t[" + column.Name + "] = @" + paramName;
}

if (column.IsInPrimaryKey)
{
if (deleteParams != "")
{
deleteParams += ",\r\n";
deleteWhere += " AND\r\n";
}
deleteParams += "\t@" + column.Name + " " + column.DataTypeNameComplete;
deleteWhere += "\t\t[" + column.Name + "] = @" + paramName;
}
}

}
%>USE [<%= database.Name %>]
GO

--|--------------------------------------------------------------------------------
--| [<%= insertProcName %>] - Insert Procedure Script for <%= tablename %>
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= insertProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= insertProcName %>]
GO

CREATE PROCEDURE [dbo].[<%= insertProcName %>]
(
<%= insertParams %>
)
AS
SET NOCOUNT ON

INSERT INTO [<%= tablename %>]
(
<%= insertFields %>
)
VALUES
(
<%= insertValues %>
)
<%= (insertAutoKeyCode == "" ? "" : "\r\n" + insertAutoKeyCode) %><%

if (hasComputedFields)
{
insertComputedCode += "\r\n\tFROM [" + tablename + "]\r\n";
insertComputedCode += "\tWHERE " + deleteWhere + ";\r\n";
}

%>
RETURN @@Error
GO

--|--------------------------------------------------------------------------------
--| [<%= updateProcName %>] - Update Procedure Script for <%= tablename %>
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= updateProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= updateProcName %>]
GO

CREATE PROCEDURE [dbo].[<%= updateProcName %>]
(
<%= updateParams %>
)
AS
SET NOCOUNT ON

UPDATE [<%= tablename %>]
SET
<%= updateSet %>
WHERE
<%= updateWhere %>
<% if (hasTimestamp) { %>
IF @@ERROR > 0
BEGIN
RAISERROR('Concurrency Error',16,1)
END
<% } %>
RETURN @@Error
GO

--|--------------------------------------------------------------------------------
--| [<%= deleteProcName %>] - Update Procedure Script for <%= tablename %>
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= deleteProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= deleteProcName %>]
GO

CREATE PROCEDURE [dbo].[<%= deleteProcName %>]
(
<%= deleteParams %>
)
AS
SET NOCOUNT ON

DELETE
FROM [<%= tablename %>]
WHERE
<%= deleteWhere %>

RETURN @@Error
GO



--|--------------------------------------------------------------------------------
--| [<%= selectProcName %>] - Update Procedure Script for <%= tablename %>
--|--------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= selectProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= selectProcName %>]
GO

CREATE PROCEDURE [dbo].[<%= selectProcName %>]
(
<%= deleteParams %>
)
AS
SET NOCOUNT ON

SELECT *
FROM [<%= tablename %>]
WHERE
<%= deleteWhere %>

RETURN @@Error
GO

<%
// Save this set of procedures to disk
output.save(filename, false);
buffer += output.text;
output.clear();
}

output.write(buffer);
%>

Thursday, October 13, 2011

How to increase session timeout on iis7

Many people ask me how to increase the session time on their web site
so here is the answer how to do that on iis7(make all the changes from the iis view):

  1. Application Pool => Advanced Settings => Process Model => Idle Time-out

  2. Sites => whatever web needs to be set => ASP => Session Properties => Time-out

  3. Sites => whatever web needs to be set => Configuration Editor => system.web/sessionState => timeout

  4. Sites => whatever web needs to be set => Configuration Editor => system.web/roleManager => cookieTimeout

Saturday, August 13, 2011

Configure a basic build server

Automation is power in software development
the exact name is continuous integration
i want to be able in one click to get latest version, build, run test and publish
this click makes me feel that i have a control on my project
in this post i'll show a basic configuration of build server
that includes:

  1. Get latest version form your source control

  2. Build your project

  3. Run your automatic testing

  4. Send an email notification with the status of the project (failed/success)


to this configuration we just have to add build trigger (schedule, on check in,...)
we also have to add an email notification to get status of the project to my email inbox


note: to run this sample you have to include your project and your test project in the same solution
you may see a sample project exactly in this structure here

my build server software is TeamCity
the build server configuration is very easy and includes 4 steps:


step 1:
-------

General Settings: nothing special in the first step, just supply a name for your project
Sample_step1


step 2:
-------

Version Control Settings: create and attach a new VCS root,
add checkout rule with the value of +:. (include all files)
and set your checkout directory (your local directory)
Sample_step2


step 3:
-------

Choose your build runner: this step inculde two sub-steps,
choose a build runner and set your test project location
the simplest runner is visual studio solution,
set your solution file and set your target and configuration fields

to set your test project you have to check the check box of run MSTest
set the path to MSTest.exe and set the path to your project test file under
List assembly files field
Sample_step3


step 4:
-------

Build Triggering: choose your build triggering,
i use a nightly scheduled build
Sample_step4


that's all now you have a build server!
just set your email notification in the project settings
a future work will be project publish with web config transforms
i hope i won't be too lazy and publish a post on it

Saturday, July 16, 2011

My Branching and Merging Strategy

Hi,
I would to share with you my way to the best practices for development version management
we always have to keep an isolated environment that is equal to the production environment because we want to keep the ability to make patches to the production environment while the other developers are working on the development iteration

my way is based on two important rules:
  1. Production environment must be equal to the main development environment for enabling production bug fixes over the iteration development

  2. The iteration development will be only in the branch development environment


I'll explain it by a simple scenario as yo can see in the chart below:

chart


legend
So, the scenario is:
1. create a branch development version from the main development version, this action occurred only once
2. in case that you have to fix a minor bug and to update the patch to the production environment, take it from the main development version
3. when the development iteration is over, we have to make merge from the main development version to the branch development version because of the production patch
4. we can update the production environment from the branch development version
5. after the version update we have to make merge from the branch development version to the main development version because we have to keep the main development version equal to the production environment

from this step we have to repeat steps 2-5 for each development iteration

one important tip:
when making the branch action, don't overwrite the configuration files, keep the target version

Monitor your system for free

Hi, I would like to introduce you a very nice system monitoring solution called
Polymon. Polymon is an easy to use software that made up of three primary components:
  • A SQL Server database to store monitor statuses, alerts and general settings.

  • A windows service (PolyMon Executive) that runs monitors on a periodic basis,
    logs results to the database and sends out email notifications.

  • A management/monitoring front-end (PolyMon Manager) that is used to manage
    general settings, monitor definitions, operators, alert rules, etc. and analyze
    historical trends (both monitor counters and statuses).

To start using this tool you have to download the latest setup file from polymon.codeplex.com setup the configuration of the software during the installation wizard and then start define the monitors that you need, then you have to set your email notifications settings, i also use one of the email to sms tools and now i get system alerts to my cell phone, i'll show here this monitors:
  • Disk Monitor - use this monitor type in case that you want to monitor the remaining free space in your system

  • File Monitor - use this monitor type in case that you want to monitor the files count on specific directory

  • MSMQ Monitor - use this monitor type in case that you want to monitor the msmq messaging service, for example, the total messages count in all the queues in the system

  • Ping Monitor - use this monitor type in case that you want to monitor the system health by a ping request

  • SQL Monitor - use this monitor type in case that you want to monitor your sql server datatbase by a structed query

  • Service Monitor - use this monitor type in case that you want to monitor your window service and check if it is still running

  • URL Monitor - use this monitor type in case that you want to monitor the a url and to make a content check on its response

Disk Monitor:

After you have selected Disk Monitor as the type of your monitor
you have to:

  1. Select the hard disk drive to monitor

  2. Set the free space remining for the warning message

  3. Set the free space remining for the failed message


polymon_diskFull





File Monitor:

After you have selected File Monitor as the type of your monitor
you have to:

  1. Select the target directory to monitor

  2. Set the search filter, probably it will be *.[file_extension]

  3. Set the file count for the warning message

  4. Set the file count for the failed message


polymon_filesNo





MSMQ Monitor:

After you have selected Performence Monitor as the type of your monitor
and select MSMQ Service as the category and select Total messages in all queues as the counter, then you have to:

  1. Set the number of messages for the warning message

  2. Set the number of messages for the failed message


polymon_MSMQ





Ping Monitor:

After you have selected Ping Monitor as the type of your monitor
you have to:

  1. Set the ip as the destination of the ping request

  2. Set the number of tries and the number of failures

  3. Set the timeout for the request


polymon_Ping





SQL Monitor:

After you have selected SQL Monitor as the type of your monitor
and wrote a stored procedure in this format you have to:

  1. Set the connection string in setting xml

  2. Set the stored procedure name in setting xml


polymon_SQL1





Service Monitor:

After you have selected Service Monitor as the type of your monitor
you have to:

  1. Set the host where the service is running

  2. Set the service name to monitor


polymon_Srv





URL Monitor:

After you have selected URL Monitor as the type of your monitor
you have to:

  1. Set url to monitor

  2. Set the request timeout

  3. Set the content to check on the response text


polymon_Url

Wednesday, October 20, 2010

Using jquery selectors on server side(C#)

Something that i have been looking for a long time
is to use jquery selectors on the server side.
if found a great solution at fizzler project
fizzler is .NET CSS Selector Engine and you can download it from here.
from fizzler site:
A .NET library to select items from a node tree based on a CSS selector. The default implementation is based on HTMLAgilityPack and selects from HTML documents

all you have to is to download fizzler package
and add reference to this dll files:
- Fizzler.Systems.HtmlAgilityPack.dll
- Fizzler.Systems.XmlNodeQuery.dll
- HtmlAgilityPack.dll

here you can see a useful samples:

HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(
@"<html>
<head></head>
<body>
<div id='content'>
<a target='_blank' href='http://yosi-havia.blogspot.com' class='FirstName'>Yosi</a>
<a href='http://yosi-havia.blogspot.com' class='LastName'>Havia</a>
</div>
</body>
</html>");
HtmlNode document = html.DocumentNode;

//@@@ get all elements with content id in html(result: 1 element)
IEnumerable<HtmlNode> list1 = document.QuerySelectorAll("#content");
List<HtmlNode> lst1 = list1.ToList<HtmlNode>();

//@@@ get all elements with FirstName class name in html(result: 1 element)
IEnumerable<HtmlNode> list2 = document.QuerySelectorAll(".FirstName");
List<HtmlNode> lst2 = list2.ToList<HtmlNode>();

//@@@ get all anchor tags in html(result: 2 elements)
IEnumerable<HtmlNode> list3 = document.QuerySelectorAll("a");
List<HtmlNode> lst3 = list3.ToList<HtmlNode>();

//@@@ get all elements in html(result: 6 elements)
IEnumerable<HtmlNode> list4 = document.QuerySelectorAll("*");
List<HtmlNode> lst4 = list4.ToList<HtmlNode>();

//@@@ get element with attribue name 'target' that starts with '_bl' in html(result: 1 element)
IEnumerable<HtmlNode> list5 = document.QuerySelectorAll("a[target^='_bl']");
List<HtmlNode> lst5 = list5.ToList<HtmlNode>();

Saturday, June 19, 2010

c# window service Debugging - the best way!

Very intresting and complicated issue is how to debug c# window service,
i saw many solutions for that but no one of them made me satisfied.

the best solution for that is to use a simple VS macro, the idea is to start the service and then attach to the process in the same macro.

you can see the macro installation instructions in this post
with a few changes:

Tuesday, March 16, 2010

Create attach to process shortcut in VS 2008

Tools -> Attach to Process... -> wait for the dialog -> < select the process > -> press on attach
who has the time and the patience to follow this step every time we want to debug an internt application.
I'll show u how to attach to process in one shortcut press.
for generate the shortcut, follow the steps below:

  1. Open Visual studio

  2. Press Alt+F11 to open MyMacros

  3. Right click on MyMacros-> Add-> Add existing item and browse to this file(change the file extension to .vb)

  4. Now, we have make a shortcut key to this macro, you should go to Tools -> Options and choose Environment -> Keyboard pane

  5. To find our macro we can search for the word macro in the search text box, and select the macro we want(in my case: Macros.MyMacros.AttachingToProcess.AttachToInternetApp)

  6. Choose a shortcut keys for this macro and insert them in the 'Press shortcut keys' text box, i choose ctrl+\ (u have to press them together)

  7. Press on Assign button, and ok, that's all, we finished


Friday, February 12, 2010

Create secure form without captcha

Usually when we want to create a secure form that computer programs cannot pass we use the captcha program.
captcha has a lot of disadvantages, when the main disadvantages is that the captcha is heavy, bother, and make users to run away from our form.
in the idea that i'll show in this post the user cannot notice in any difference from unsecured form.
the steps for the very simple solution is

1. generate a random names to inputs in the form
2. save the names in the session collection at the server side
3. after the user submits the forn, take the inputs names fron rhe session
4. the the inputs values from the request collection with the key names from the session

take a look at this simple example at asp .net but it will work in every server side language:
---------------------------------------------------------------------------------------
the server side code

public partial class _Default : System.Web.UI.Page
{
public string UserNameKey;
public string PasswordKey;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["UserNameKey"] = UserNameKey = Guid.NewGuid().ToString();
Session["PasswordKey"] = PasswordKey = Guid.NewGuid().ToString();
}
}
protected void lnkSend_Click(object sender, EventArgs e)
{
if (Session["UserNameKey"] != null
&& Session["PasswordKey"] != null)
{
string UserNameValue = Request[Session["UserNameKey"].ToString()];
string PasswordValue = Request[Session["PasswordKey"].ToString()];
}
}
}


the html code

<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
User name: <input type="text" name="<%=UserNameKey%>" />
<br />
Password: <input type="password" name="<%=PasswordKey%>" />
<br />
<asp:LinkButton ID="lnkSend" runat="server"
onclick="lnkSend_Click" >Send</asp:LinkButton>
</form>
</body>
</html>

Monday, September 14, 2009

Simple xslt example

In this post i'll show how 2 make a simple xsl transform.
In addition i'll show how to use this xsl elements:

1. XsltArgumentList - pass arguments to the xslt
2. Encoding - declare the outgoing xml encoding
3. xsl:value-of - take the value(inner text) of node
4. xsl:copy-of - copy the inner xml of node
5. xsl:for-each - loop through same nodes
6. xsl:sort - sort nodes by specified node

and in the end of the post there is a c# thread safety class to make xsl transforms

so, this is the origin xml file(Person.xml):

<hPerson>
<Header>

<FirstName>Yosi</FirstName>
<LastName>Havia</LastName>
<Age>30</Age>
<Education>BA</Education>
</Header>
<hChildren>
<hChild>
<hName>Carol</hName>
<hAge>13</hAge>
</hChild>
<hChild>
<hName>Angela</hName>
<hAge>15</hAge>
</hChild>
<hChild>
<hName>Benjamin</hName>
<hAge>17</hAge>
</hChild>
</hChildren>
</hPerson>


and this is the xslt file(Person.xslt):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes" omit-xml- declaration="yes"/>
<xsl:param name="Gender"></xsl:param>
<xsl:template match="/">
<Person>
<Gender>
<xsl:choose>
<xsl:when test="$Gender='1'">
Male
</xsl:when>
<xsl:otherwise>
Female
</xsl:otherwise>
</xsl:choose>
</Gender>
<xsl:copy-of select="/hPerson/Header"/>
<Data>
<Children>
<xsl:for-each select="/hPerson/hChildren/hChild">
<xsl:sort select="hName" />
<Child>
<FirstName>
<xsl:value-of select="hName"/>
</FirstName>
<Age>
<xsl:value-of select="hAge"/>
</Age>
</Child>
</xsl:for-each>
</Children>
</Data>
</Person>
</xsl:template>
</xsl:stylesheet>

the output xml look like this:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
<Gender>
Male
</Gender>
<Header>
<FirstName>Yosi</FirstName>
<LastName>Havia</LastName>
<Age>30</Age>
<Education>BA</Education>
</Header>
<Data>
<Children>
<Child>
<FirstName>Angela</FirstName>
<Age>15</Age>
</Child>
<Child>
<FirstName>Benjamin</FirstName>
<Age>17</Age>
</Child>
<Child>
<FirstName>Carol</FirstName>
<Age>13</Age>
</Child>
</Children>
</Data>
</Person>

this is a thread safety c# class to make xsl transforms

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace XSLT
{
class XsltObj
{
protected static XslCompiledTransform _oXslTransform;
protected static object _oSyncXsl = new object();
public string FormatXmlWrapper(string sEncoding, XsltArgumentList
oXsltArgumentList,XmlDocument oOriginXmlDoc, string sXslPath)
{
string sRetVal = null;
if (_oXslTransform == null)
{
LoadXslWrapper(sXslPath, ref _oXslTransform, ref _oSyncXsl);
}
//@@@ make the transform
try
{
sRetVal = TransformData(sEncoding, _oXslTransform, oOriginXmlDoc,
oXsltArgumentList);
}
catch (Exception ex)
{
throw ex;
}
return sRetVal;
}
protected void LoadXslWrapper(string sXslPath,
ref XslCompiledTransform oXslTransform, ref object oSyncXsl)
{
lock (oSyncXsl)
{
if (oXslTransform == null)
{
XslCompiledTransform oTempXslTransform =
new XslCompiledTransform();
//@@@ get the xml path from configuration
LoadXsl(sXslPath, ref oTempXslTransform);
oXslTransform = oTempXslTransform;
}
}
}
protected void LoadXsl(string sXslPath, ref XslCompiledTransform
oXslCompiledTransform)
{
//@@@ load the xsl document(only once)
XmlDocument xslDocument = new XmlDocument();
XmlUrlResolver urlResolver = new XmlUrlResolver();
urlResolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
xslDocument.XmlResolver = urlResolver;
try
{
//@@@ load the xsl document
xslDocument.Load(sXslPath);
XPathNavigator oXPathNavigator = xslDocument.CreateNavigator();
oXslCompiledTransform.Load(oXPathNavigator,
XsltSettings.TrustedXslt, urlResolver);
}
catch (Exception ex)
{
throw ex;
}
}
protected string TransformData(string sEncoding, XslCompiledTransform
oXslTransform, XmlDocument xmlDocument, XsltArgumentList argumentList)
{
StringBuilder sb = new StringBuilder();
string sDeclaration;
//@@@ decide the xml declaration up to the Encoding
if (string.IsNullOrEmpty(sEncoding))
sDeclaration = "version=\"1.0\"";
else
sDeclaration = "version=\"1.0\" encoding=\"" + sEncoding + "\"";
//@@@ make the xsl Transform
using (XmlWriter output = XmlWriter.Create(sb))
{
output.WriteProcessingInstruction("xml", sDeclaration);
XPathNavigator oXPathNavigator = xmlDocument.CreateNavigator();
oXslTransform.Transform(oXPathNavigator, argumentList, output);
return sb.ToString();
}
}
}
}

to activate this object use this code:

static void Main(string[] args)
{
XsltObj oXsltObj = new XsltObj();
XsltArgumentList oXsltArgumentList = GetXsltArguments();
XmlDocument oXmlDocument = new XmlDocument();
string sXmlPath = @"Person.xml";
string sXslPath = @"Person.xslt";
oXmlDocument.Load(sXmlPath);
string sXml = oXsltObj.FormatXmlWrapper("UTF-8", oXsltArgumentList,
oXmlDocument, sXslPath);
}
protected static XsltArgumentList GetXsltArguments()
{
//@@@ create the arguments for the xsl
XsltArgumentList list = new XsltArgumentList();
list.AddParam("Gender", string.Empty, "1");
return list;
}

Wednesday, August 19, 2009

force download of remote file

Many times we want 2 enable 2 users to download files from our web site
just put this function in the Page_Load function and then the users will be enable to download remote files from any web site (note that the function parameter is a virtual path!):

private void forceDownloadRemoteFile(string sFileVirtualPath)
{
string sFileName = System.IO.Path.GetFileName(sFileVirtualPath);
WebClient oWebClient = new WebClient();
MemoryStream oMemoryStream;
try
{
byte[] bytes = oWebClient.DownloadData(sFileVirtualPath);
oMemoryStream = new MemoryStream(bytes);
}
finally
{
oWebClient.Dispose();
}
BinaryReader oBinaryReader = new BinaryReader(oMemoryStream);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}", sFileName));
Response.BinaryWrite(oBinaryReader.ReadBytes((int)oMemoryStream.Length));

oBinaryReader.Close();

Response.Flush();
Response.End();
}

To execute this function u can use this code:

protected void Page_Load(object sender, EventArgs e)
{
string sFileVirtualPath = @"http://localhost/TryWebSite/TextFile.txt";
forceDownloadRemoteFile(sFileVirtualPath);
}

Saturday, August 8, 2009

How to transform between object and xml in c#

Hi,
Many times we need 2 make transforms object to xml and transform xml to object.
there is a very simple way in XmlSerializer class, we just have to call serialize or Deserialize function and we can get what want. I'll explain it by example:


let's say that we have RootData class:

public class RootData
{
public HeaderElement Header;
public List SubjectsList;
}
public class HeaderElement
{
public int DataType;
}
public class Subject
{
public string SubjectName;
public int SubjectID;
public int SubjectType;
}

and we need to make transforms with this xml:

<?xml version="1.0" encoding="utf-8"?>
<RootData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Header>
<DataType>1</DataType>
</Header>
<SubjectsList>
<Subject>
<SubjectName>Name1</SubjectName>
<SubjectID>1</SubjectID>
<SubjectType>1</SubjectType>
</Subject>
<Subject>
<SubjectName>Name2</SubjectName>
<SubjectID>2</SubjectID>
<SubjectType>2</SubjectType>
</Subject>
<Subject>
<SubjectName>Name3</SubjectName>
<SubjectID>3</SubjectID>
<SubjectType>3</SubjectType>
</Subject>
</SubjectsList>
</RootData>


The function 2 make transform from object to xml is:

public string SerializeObject(Type oType, object oRootData)
{
//@@@ Create xml from the object
MemoryStream oMemoryStream = null;
XmlTextWriter oXmlTextWriter = null;
string sXml = null;
try
{
oMemoryStream = new MemoryStream();
XmlSerializer oXmlSerializer = new XmlSerializer(oType);
oXmlTextWriter = new XmlTextWriter(oMemoryStream, Encoding.UTF8);
oXmlSerializer.Serialize(oXmlTextWriter, oRootData);
oMemoryStream = (MemoryStream)oXmlTextWriter.BaseStream;
UTF8Encoding oUTF8Encoding = new UTF8Encoding();
sXml = oUTF8Encoding.GetString(oMemoryStream.ToArray());
}
catch (Exception)
{
throw;
}
finally
{
if (oMemoryStream != null)
oMemoryStream.Close();
if (oXmlTextWriter != null)
oXmlTextWriter.Close();
}
return sXml;
}

The function 2 make transform from xml to object is:

public object DeserializeObject(Type oType, string sXml)
{
//@@@ Create object from the xml
MemoryStream oMemoryStream = null;
object oRootData = null;
try
{
XmlSerializer oXmlSerializer = new XmlSerializer(oType);
UTF8Encoding oUTF8Encoding = new UTF8Encoding();
Byte[] Bytes = oUTF8Encoding.GetBytes(sXml);
oMemoryStream = new MemoryStream(Bytes);
oRootData = oXmlSerializer.Deserialize(oMemoryStream);
}
catch (Exception)
{
throw;
}
finally
{
if (oMemoryStream != null)
oMemoryStream.Close();
}
return oRootData;
}

Before u run this example, u can fill your object with this function:

public RootData CreateData()
{
RootData oRootData = new RootData();
HeaderElement oHeaderElement = new HeaderElement();
oHeaderElement.DataType = 1;
oRootData.Header = oHeaderElement;

Subject oSubject1 = new Subject();
oSubject1.SubjectID = 1;
oSubject1.SubjectName = "Name1";
oSubject1.SubjectType = 1;

Subject oSubject2 = new Subject();
oSubject2.SubjectID = 2;
oSubject2.SubjectName = "Name2";
oSubject2.SubjectType = 2;

Subject oSubject3 = new Subject();
oSubject3.SubjectID = 3;
oSubject3.SubjectName = "Name3";
oSubject3.SubjectType = 3;

List Subjects = new List();
Subjects.Add(oSubject1);
Subjects.Add(oSubject2);
Subjects.Add(oSubject3);

oRootData.SubjectsList = Subjects;
return oRootData;
}

And run this code to execute the transform:

RootData oRootData = CreateData();
string sXml = SerializeObject(typeof(RootData), oRootData);
oRootData = (RootData)DeserializeObject(typeof(RootData), sXml);


In this case when every data member trnsform 2 xml node we dont have to change or add nothing in the class, but there is a few useful attributes that we can use (just add it above the data member class):

  • [XmlElement("<Xml Node Name>")] - by default, the XmlSerializer uses the data member name as the xml node name, if u want 2 change it - use this attribute

  • [XmlElement(("<Xml Node Name>"), IsNullable = false)] - says that if the data member value is null it will not appear in the transformed xml

  • [XmlAttribute] - use it when u want that the data member output will be xml attribute and not xml node

Saturday, July 25, 2009

How to identify user's country by ip

In a 4 steps u can identify the user's country
u will discover that it is a very easy assignment

step 1:
-------
Download the txt file from here, that represent the ip ranges of each country. when u save this file change his extension to csv.

step 2:
-------
Import the csv file into your db and create table with the name [ip-to-country].

step 3:
-------
By taking the user's IP with Request.UserHostAddress convert this string to uint by this function:

public uint IPAddressToLongBackwards(string IPAddr)
{
System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
byte[] byteIP = oIP.GetAddressBytes();

uint ip = (uint)byteIP[0] << 24;
ip += (uint)byteIP[1] << 16;
ip += (uint)byteIP[2] << 8;
ip += (uint)byteIP[3];

return ip;
}


step 4:
-------
with this ip address (as uint) go to our [ip-to-country] table and select the country by this sql query(@ip is the uint ip address):

SELECT countryCode2
from [ip-to-country]
where ipFrom <= @ip
and ipTo >= @ip

Sunday, May 24, 2009

ContainsKey problem

Hi,
In case that u have generic Dictionary with non primitive key - ContainsKey function will return u a bad answer because this function compare objects by refrence an NOT by value!
so, if u have same key values in the Dictionary and in your test object u will get negative answer.
the solution is 2 override Equals and GetHashCode functions:


//@@@ I have Dictionary with Key_Event5 object as the key
Dictionary<Key_Event5, Event5_Employment> dictEmployment;
//@@@ 4 support ContainsKey function compare by value, i'll implement Key_Event5 on this way:
public class Key_Event5
{
public int iFormID { get; set; }
public int iEmploymentCode { get; set; }
public Key_Event5(int iFormID, int iEmploymentCode)
{
this.iFormID = iFormID;
this.iEmploymentCode = iEmploymentCode;
}

public override bool Equals(object obj)
{
Key_Event5 oKey_Event5 = obj as Key_Event5;
if (oKey_Event5 == null)
return false;
//@@@ Compare by iFormID and iEmploymentCode
return Equals(iFormID, oKey_Event5.iFormID)
&& Equals(iEmploymentCode, oKey_Event5.iEmploymentCode);

}
public override int GetHashCode()
{
return iFormID.GetHashCode() ^ iEmploymentCode.GetHashCode();
}

}
//@@@ And now this line will work
dictEmployment.ContainsKey(oKey_Event5)

Simple XPath Examples

Hi,
In this post i'll show some simple(but useful) XPath Examples
let's say that i have this xml file named 'Persons.xml':


<?xml version='1.0'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>


so, let's talk code lines:


//@@@ Select all the persons in 18 age
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age = '" + 18 + "']");


//@@@ Select all the persons with age greater than 17
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age > '" + 17 + "']");


//@@@ Select all the persons that contains Yosi in their names
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person/FullName[contains(.,'" + "Yosi" + "')]");


//@@@ Select all the persons with 180 height(attribute)
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[@Height = '" + "180" + "']");

Saturday, May 9, 2009

How to merge 2 XmlDocuments

Hi,
In this post i'll show u how 2 merge 2 xml documents
let's say that i have 2 xml documents,

Persons.xml

<?xml version='1.0'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>



and Persons2.xml

<?xml version='1.0'?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

</Persons>



What i want 2 do in this example is 2 take the node with the full name 'Yosi Havia' from Persons2.xml file and replace the original node with the same full name in Persons.xml file.
this code lines make this assigment(with help of my last post Simple XPath Examples ):

XmlDocument XmlPersons1 = new XmlDocument();
XmlPersons1.Load(@"Persons.xml");

XmlDocument XmlPersons2 = new XmlDocument();
XmlPersons2.Load(@"Persons2.xml");

XmlNode oXmlNewData = XmlPersons2.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
XmlNode targetNode = XmlPersons1.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
//@@@ Add the node from XmlPersons2.xml to XmlPersons.xml
XmlNode sourceNode = XmlPersons1.ImportNode(oXmlNewData, true);
//@@@ Replace the original node
XmlPersons1.DocumentElement.ReplaceChild(sourceNode, targetNode);

and u can c the result here:

<?xml version="1.0"?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>

Wednesday, May 6, 2009

Performence check in c# with Stopwatch

Hi,
System.Diagnostics has a very nice object called Stopwatch
i show here my very easy and simple example 4 making performence check:

Stopwatch oStopwatch = new Stopwatch();
oStopwatch.Start();
//@@@ Start of code to make the performence check
Thread.Sleep(3000);
//@@@ End of code to make the performence check
oStopwatch.Stop();
TimeSpan oTimeSpan = oStopwatch.Elapsed;
Console.WriteLine(oTimeSpan.ToString());


the output of this code was:

00:00:02.9994520