tag:blogger.com,1999:blog-75337008733715134822024-03-12T18:23:39.882-07:00Yosi HaviaYosi Havia 's c# web development blog.
הבלוג של יוסי חביה נושאי תכנות שוניםYosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.comBlogger28125tag:blogger.com,1999:blog-7533700873371513482.post-39340019130829719722012-01-03T12:57:00.000-08:002012-01-04T12:41:03.471-08:00Replace task manager with process explorer<a target="_blank" href="http://technet.microsoft.com/en-us/sysinternals/bb896653">Process Explorer</a> 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<br /><br />You also have the option to replace the traditional Task Manager by the Process Explorer software menu: Options-> Replace Task Manager<br /><br /><img src="https://sites.google.com/site/yosihaviablogfiles/files-container/ProcessExplorer.jpg"/>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-26093078554951822822011-12-25T12:36:00.000-08:002011-12-25T12:58:09.772-08:00Simple cache providerInstead 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, <br />the function improve your code concentration and פrevents code replication<br />the function has 3 arguments:<br />- cacheKey - the key name to use in the cache object<br />- getfromDbFunc - this function will call in case that the cache is empty<br />- param - the parameter will be send to getfromDbFunc function<br /><br /><pre name="code" class="c-sharp"><br />public class CacheProvider<br />{<br /> public T GetData<T, P>(string cacheKey, <br /> Func<P, T> getfromDbFunc, object param) where T : class<br /> {<br /> T item = HttpRuntime.Cache.Get(cacheKey) as T;<br /> P p = (P)param;<br /> if (item == null)<br /> {<br /> item = getfromDbFunc(p);<br /> HttpContext.Current.Cache.Insert(cacheKey, item, null,<br /> DateTime.UtcNow.AddMinutes(10),<br /> System.Web.Caching.Cache.NoSlidingExpiration);<br /> }<br /> return item;<br /> }<br />}<br /></pre><br /><br />Example how to use:<br /><pre name="code" class="c-sharp"><br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> CacheProvider cacheProvider = new CacheProvider();<br /> int userid = 17;<br /> var user = cacheProvider.GetData<string, int>("user_" + userid, getUser, userid);<br /> }<br /> public string getUser(int id)<br /> {<br /> //TODO: retrieve user from db<br /> return "newuser";<br /> }<br /></pre>I'll be glad to get suggestions or improvementsYosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-5146662491330762972011-11-29T23:05:00.000-08:002011-11-30T01:25:45.445-08:00My first Windows Phone app: SelfTimer++<img src="https://sites.google.com/site/yosihaviablogfiles/files-container/CameraPaintFIXED_99.png"/><br /><br />Hi,<br />I am proud to introduce you my first Windows Phone app: SelfTimer++<br /><br />SelfTimer++ gives a delay between pressing the shutter release and the shutter's firing.<br />Once you push the button, a countdown sound is emitted.<br />There is no setting page, setting is on camera screen<br />A trial version is also available with ads <br />Features:<br />- Self timer with countdown on screen and countdown sound<br />- Output tone: Grayscale, Sepia, Negative<br />- Set up shots in sequences of 2, 3, 4 or 5 photographs<br />- Autofocus and Tap to focus<br />- Resolution settings<br />- Silent mode<br />- Last capture image view<br /><br /><a target="_blank" href="http://windowsphone.com/s?appid=4e8b0372-2a2f-432d-88b3-86b3fc016463"><img src="https://sites.google.com/site/yosihaviablogfiles/files-container/Download-EN-Med.png" border="0"/></a>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-79808400774355472552011-11-01T00:48:00.000-07:002011-11-01T03:18:18.559-07:00How to auto generate codeI think that, at least, something like 50% of our code is very structed and simple <br />and can be done by an auto generated code tool and there is no need <br />to write this code manually,<br />the main advantages of using auto generated code tool are:<ol><br /><li><b>Saves time</b> - don't waste your time on the simple actions, waste your time on the complicated algorithm</li><br /><li><b>Systemic change</b> - for example if we want to add a new field to all the entities in the system<br />we can do it in a one central place instead of to change each entity<br /><li><b>better code</b> - the code is clean and simple</li><br /><li><b>coding standards built in</b> - there is no need to make code reviews, the code is structed and known to everyone</li><br /></li><br /></ol>in my sample below i use <a href="http://www.mygenerationsoftware.com" target="_blank">MyGeneration</a> auto generated tool<br />that it is a very easy to use tool<br /><br />lets say that i have a Persons table in my db(see the table code below)<br />and i want to create <a href="#cs">c# code</a> and <a href="#sql">sql procedures</a> for this entity<br /><br /><pre name="code" class="sql"><br />create TABLE [dbo].[Persons](<br /> [ID] [int] IDENTITY(1,1) NOT NULL,<br /> [Name] [nvarchar](50) NULL,<br /> [Counter] [int] NULL,<br /> [BirthDate] [datetime] NULL,<br />CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED <br />(<br /> [ID] ASC<br />)<br />) ON [PRIMARY]<br /><br />GO<br /></pre><br /><br /><a name="cs"></a><br /><div style="font-size:16px;font-weight:bold">Code Generated</div>I want to create this basic c# classes that will represent this table:<br /><ol><br /><li><b>PersonBase</b> - a class that contains all the fields of person</li><br /><li><b>IPerson</b> - an interface that contains all the fields of person</li><br /><li><b>Person</b> - a class that containd the logic of the entity</li><br /></ol>the idea is to update the template code in the MyGeneration template<br />that is based on this code lines:<br /><br /><pre name="code" class="c-sharp"><br /><% <br />foreach (string columnName in columns)<br />{<br /> columnAlias = DnpUtils.SetCamelCase(DnpUtils.TrimSpaces(table.Columns[columnName].Alias)); <br /> columnLanguageType = table.Columns[columnName].LanguageType;<br /> %><br /> private <%=columnLanguageType%> _<%=columnAlias%>;<br /> <%<br />}<br />%><br /></pre><br />which means that the lines in the yellow parentheses are the logic to manipulate your <br />auto generate code and all the other lines are the auto generated code output<br />in this sample i make a loop through all the columns of the table and create a<br />private data member in c#<br /><br />you may see the output of this c# code template below:<br /><br /><div style="overflow-y:scroll;height:250px;border:solid grey 1px"><br /><br /> <br /> <br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************<br />*<br />*<br />* PersonBase - A Class Representing Persons' fields/columns <br />*<br />*<br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************/<br /><br /><br />using System;<br />using System.Text;<br />using System.Data;<br /><br />namespace My.Framework.Core.Application<br />{<br /> [Serializable()]<br /> public class PersonBase : IMyObject<br /> { <br /> #region MyGeneration Auto-Generated Code<br /> <br /> #region fields<br /> private int _id;<br /> private string _name;<br /> private int? _counter;<br /> private DateTime _birthDate = DateTime.MinValue;<br /> <br /> #endregion<br /> <br /> #region properties<br /> <br /> public int Id<br /> {<br /> get { return _id; }<br /> set { _id = value;}<br /> }<br /> <br /> public string Name<br /> {<br /> get { return _name; }<br /> set { _name = value;}<br /> }<br /> <br /> public int? Counter<br /> {<br /> get { return _counter; }<br /> set { _counter = value;}<br /> }<br /> <br /> public DateTime BirthDate<br /> {<br /> get { return _birthDate; }<br /> set { _birthDate = value;}<br /> }<br /> #endregion<br /> <br /> #region Constructors<br /> <br /> public PersonBase(){}<br /> public PersonBase(IDataReader reader)<br /> {<br /> <br /> this._id = (int)Convert.ChangeType(reader["ID"], typeof(int));<br /> if (!reader.IsDBNull(reader.GetOrdinal("Name")))<br /> { <br /> this._name = (string)Convert.ChangeType(reader["Name"], typeof(string));<br /> }<br /> if (!reader.IsDBNull(reader.GetOrdinal("Counter")))<br /> { <br /> this._counter = (int)Convert.ChangeType(reader["Counter"], typeof(int));<br /> }<br /> if (!reader.IsDBNull(reader.GetOrdinal("BirthDate")))<br /> { <br /> this._birthDate = (DateTime)Convert.ChangeType(reader["BirthDate"], typeof(DateTime));<br /> }<br /> }<br /> public PersonBase(int id, string name, int? counter, DateTime birthDate)<br /> {<br /> this._id = id;<br /> this._name = name;<br /> this._counter = counter;<br /> this._birthDate = birthDate;<br /> }<br /> <br /> #endregion<br /> <br /> #region IMyObject Members<br /> <br /> public DateTime Created<br /> {<br /> get { return DateTime.MinValue; }<br /> set { throw new NotImplementedException(); }<br /> }<br /><br /> public DateTime Deleted<br /> {<br /> get { return DateTime.MinValue; }<br /> set { throw new NotImplementedException(); }<br /> }<br /><br /> public DateTime Updated<br /> {<br /> get { return DateTime.MinValue; }<br /> set { throw new NotImplementedException(); }<br /> }<br /> <br /> #endregion<br /> <br /> #endregion<br /> }<br />}<br /><br /><br /><br /><br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************<br />*<br />*<br />* IPerson - An Interface representing Persons<br />*<br />*<br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************/<br /><br /><br />using System;<br />using System.Text;<br />using System.Data;<br />using My.BusinessLogic.DataAccess;<br />using My.Framework;<br />using My.Framework.Core.Application;<br />using My.BusinessLogic.Application;<br /><br />namespace My.BusinessLogic<br />{<br /> public interface IPerson <br /> { <br /> #region MyGeneration Auto-Generated Code<br /> <br /> #region properties<br /> int Id{get;set;}<br /> string Name{get;set;}<br /> int? Counter{get;set;}<br /> DateTime BirthDate{get;set;}<br /> #endregion<br /> <br /> #endregion<br /> }<br />}<br /><br /><br /><br /><br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************<br />*<br />*<br />* Person BL's Class Code<br />*<br />*<br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************/<br /><br /><br />using System;<br />using System.Text;<br />using System.Data;<br />using My.BusinessLogic.DataAccess;<br />using My.Framework;<br />using My.Framework.Core.Application;<br />using My.BusinessLogic.Application;<br /><br />namespace My.BusinessLogic<br />{<br /> [Serializable]<br /> public class Person : PersonBase,IPerson<br /> {<br /> #region MyGeneration Auto-Generated Code<br /> <br /> #region Constructors<br /> <br /> public Person() : base() <br /> {}<br /> public Person(IDataReader reader) : base(reader) <br /> {}<br /> <br /> <br /> public Person(int id, string name, int? counter, DateTime birthDate) : <br /> base(id, name, counter, birthDate) {}<br /> <br /> #endregion<br /> <br /> <br /> #region ISchemaDataObject Members<br /> <br /> public bool Save(ISession session)<br /> {<br /> if (Id == -1) //Insert<br /> {<br /> Id = session.GetDataSource<ApplicationDataSource>().Insert(this);<br /> }<br /> else //Update<br /> {<br /> session.GetDataSource<MasterDataSource>().Update(this);<br /> }<br /> return true;<br /> }<br /> <br /> public bool Delete(ISession session)<br /> {<br /> throw new NotImplementedException("Delete wasn't generated, kindly implement it please.");<br /> }<br /> <br /> #endregion<br /> <br /> <br /> #endregion<br /> }<br />}<br /><br /><br /><br /><br /><br /><br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************<br />*<br />*<br />* SQL - Stored Procedures<br />*<br />*<br />/**************************************************************************************************<br />/**************************************************************************************************<br />/**************************************************************************************************<br /><br />Get From the 2nd util..<br /></div><br /><br />and download the full template <a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/BasicTemplateYosi_CODE.zeus">here</a><br /><br /><br /><a name="sql"></a><br /><div style="font-size:16px;font-weight:bold">Sql Generated</div>I want to create this basic sql procedure that will represent this table:<br /><ol><br /><li><b>SP_Person_Insert</b> - a procedure that insert a new person</li><br /><li><b>SP_Person_Update</b> - a procedure that update an existing person</li><br /><li><b>SP_Person_Delete</b> - a procedure that delete an existing person</li><br /><li><b>SP_GetPerson_ByID</b> - a procedure that return the requested person</li> <br /></ol>here the idea is a little bit different<br />the idea is to create a list of fields (for example: [Name], [Counter], [BirthDate])<br />and list of values (for example: @Name, @Counter, @BirthDate)<br />and to use it in the output of the template<br />i recommend you to download the full template from <a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/BasicTemplateYosi_SQL.zeus">here</a> <br />and to customize it as you wish<br /><br />you may see the output of this sql procedure template below:<br /><br /><div style="overflow-y:scroll;height:250px;border:solid grey 1px"><br /><% <br />//------------------------------------------------------------------------------<br />// SQL_StoredProcs.jgen<br />// Last Update : 2/21/2004<br />//<br />// Be sure to rename this template if you plan to customize it, MyGeneration <br />// Software will update this sample over time.<br />//------------------------------------------------------------------------------<br />//<br />// This template generates 3 stored procedures<br />//<br />// 1) [TableName]Update<br />// 2) [TableName]Insert<br />// 3) [TableName]Delete<br />//<br />// There is script in the "Interface Code" tab that pops up a dialog so you can tell this tempate<br />// where to save the files and what tables you want to generate stored procedures for. So, the<br />// logic at a very high level looks like this:<br />//<br />// For Each TableName in Select Tables<br />// objTable = database.Tables.Item(TableName)<br />// Generate the 3 stored procs for objTable<br />// Save file<br />// Next<br />//<br />// However, all of the script ends up in the Output tab and you can copy this right into <br />// Sql QueryAnalyzer and execute it. It's a pretty smart template, it knows to make<br />// Identity Columns output parameters to return them, the same holds true for computed<br />// Columns. It knows how to use PrimaryKeys in WHERE clauses and not to update them<br />// in the UpdateStored Proc, if you have a TimeStamp it will do the comparison for you and <br />// so on. This template alone can save you tons of time, and at anytime you can regenerate<br />// them as tables change.<br />//------------------------------------------------------------------------------<br />// Justin Greenwood<br />// MyGeneration Software<br />// justin.greenwood@mygenerationsoftware.com<br />// http://www.mygenerationsoftware.com/<br />//------------------------------------------------------------------------------<br /><br />// collect needed data/objects and put them in local variables<br />var databaseName = input.Item("cmbDatabase"); <br />var tablenames = input.Item("lstTables"); <br />var database = MyMeta.Databases.Item(databaseName);<br /><br />// Filename info<br />var filepath = input.item("txtPath");<br />if (filepath.charAt(filepath.length - 1) != '\\') filepath += "\\";<br /><br />// The buffer that will hold all the output for rendering.<br />var buffer = "";<br /><br />for (var i = 0; i < tablenames.Count; i++)<br />{<br /> var tablename = tablenames.item(i);<br /> var tableMeta = database.Tables.Item(tablename);<br /> <br /> // Single name<br /> var tableNameSingle = DnpUtils.SetPascalCase(DnpUtils.TrimSpaces(tableMeta.Alias));;<br /><br /> if (tableNameSingle.match("ies$") == "ies") // ends with<br /> tableNameSingle = tableNameSingle.substr(0, tableNameSingle.length - 3) + "y";<br /> else if (tableNameSingle.match("s$") == "s") // ends with<br /> tableNameSingle = tableNameSingle.substr(0, tableNameSingle.length - 1);<br /> <br /><br /> // Build the filename<br /> var filename = filepath + "sql_procs_" + tablename + ".sql"<br /><br /> var insertProcName = "SP_" + tableNameSingle + "_Insert";<br /> var insertParams = "";<br /> var insertFields = "";<br /> var insertValues = "";<br /> var insertAutoKeyCode = "";<br /> var insertComputedCode = "";<br /><br /> var updateProcName = "SP_" + tableNameSingle + "_Update";<br /> var updateParams = "";<br /> var updateSet = "";<br /> var updateWhere = "";<br /><br /> var deleteProcName = "SP_" + tableNameSingle + "_Delete";<br /> var selectProcName = "SP_Get" + tableNameSingle + "_ByID";<br /> var deleteParams = "";<br /> var deleteWhere = "";<br /><br /> var paramName = "";<br /><br /> var hasComputedFields = false;<br /> var hasTimestamp = false;<br /><br /> // Loop through all the columns of the table <br /> for (var j = 0; j < tableMeta.Columns.Count; j++) <br /> {<br /> column = tableMeta.Columns.Item(j);<br /> paramName = column.Name.split(' ').join('')<br /><br /> // If the datatype is not a timestamp, add it to the insert statement<br /> if (column.DataTypeName == "timestamp")<br /> {<br /> hasTimestamp = true;<br /> }<br /> else if (!column.IsComputed)<br /> {<br /> if (insertParams != "")<br /> {<br /> insertParams += ",\r\n";<br /> }<br /> if (insertFields != "")<br /> {<br /> insertFields += ",\r\n";<br /> insertValues += ",\r\n";<br /> }<br /><br /> insertParams += "\t@" + paramName + " " + column.DataTypeNameComplete<br /> <br /> if ((column.DataTypeName == "uniqueidentifier") && (column.IsInPrimaryKey) && (tableMeta.PrimaryKeys.Count == 1))<br /> {<br /> insertParams += " = NEWID() OUTPUT";<br /> }<br /> else if (column.IsNullable || column.IsAutoKey || column.IsComputed)<br /> {<br /> insertParams += " = NULL";<br /> <br /> if (column.IsAutoKey || column.IsComputed)<br /> {<br /> insertParams += " OUTPUT";<br /> }<br /> }<br /><br /> if (!column.IsAutoKey && !column.IsComputed)<br /> {<br /> insertFields += "\t\t[" + column.Name + "]";<br /> insertValues += "\t\t@" + paramName;<br /> }<br /> }<br /><br /> if (column.IsAutoKey)<br /> {<br /> insertAutoKeyCode += "\tSELECT @" + paramName + " = SCOPE_IDENTITY();\r\n";<br /> }<br /><br /> if (column.IsComputed)<br /> {<br /> if (insertComputedCode == "") <br /> {<br /> hasComputedFields = true;<br /> insertComputedCode += "\tSELECT ";<br /> }<br /> else<br /> {<br /> insertComputedCode += ", \r\n";<br /> }<br /> insertComputedCode += "\t\t@" & paramName & " = [" & column.Name & "]" <br /> }<br /><br /> if (!column.IsComputed)<br /> {<br /> if (updateParams != "")<br /> {<br /> updateParams += ",\r\n";<br /> }<br /> <br /> updateParams += "\t@" + paramName + " " + column.DataTypeNameComplete;<br /> if (column.IsNullable || column.IsComputed || column.DataTypeName == "timestamp")<br /> {<br /> updateParams += " = NULL";<br /> <br /> if (column.IsComputed)<br /> {<br /> updateParams += " output";<br /> }<br /> }<br /> <br /> <br /> if (column.IsInPrimaryKey || column.DataTypeName == "timestamp")<br /> {<br /> if (updateWhere != "")<br /> {<br /> updateWhere += " AND\r\n";<br /> }<br /> <br /> if (column.DataTypeName == "timestamp") <br /> {<br /> updateWhere += "\t\tTSEQUAL(" + column.Name + ", @" + paramName + ")";<br /> }<br /> else<br /> {<br /> updateWhere += "\t\t[" + column.Name + "] = @" + paramName;<br /> }<br /> }<br /> <br /> if (!column.IsComputed && !column.IsAutoKey && column.DataTypeName != "timestamp")<br /> {<br /> if (updateSet != "")<br /> {<br /> updateSet += ",\r\n";<br /> }<br /> <br /> updateSet += "\t\t[" + column.Name + "] = @" + paramName;<br /> }<br /> <br /> if (column.IsInPrimaryKey)<br /> {<br /> if (deleteParams != "")<br /> {<br /> deleteParams += ",\r\n";<br /> deleteWhere += " AND\r\n";<br /> }<br /> deleteParams += "\t@" + column.Name + " " + column.DataTypeNameComplete;<br /> deleteWhere += "\t\t[" + column.Name + "] = @" + paramName;<br /> }<br /> }<br /><br /> }<br />%>USE [<%= database.Name %>]<br />GO<br /><br />--|--------------------------------------------------------------------------------<br />--| [<%= insertProcName %>] - Insert Procedure Script for <%= tablename %><br />--|--------------------------------------------------------------------------------<br />IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= insertProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= insertProcName %>]<br />GO<br /><br />CREATE PROCEDURE [dbo].[<%= insertProcName %>]<br />(<br /><%= insertParams %><br />)<br />AS<br /> SET NOCOUNT ON<br /><br /> INSERT INTO [<%= tablename %>]<br /> (<br /><%= insertFields %><br /> )<br /> VALUES<br /> (<br /><%= insertValues %><br /> )<br /><%= (insertAutoKeyCode == "" ? "" : "\r\n" + insertAutoKeyCode) %><%<br /><br />if (hasComputedFields) <br />{<br /> insertComputedCode += "\r\n\tFROM [" + tablename + "]\r\n";<br /> insertComputedCode += "\tWHERE " + deleteWhere + ";\r\n";<br />}<br /><br />%><br /> RETURN @@Error<br />GO<br /><br />--|--------------------------------------------------------------------------------<br />--| [<%= updateProcName %>] - Update Procedure Script for <%= tablename %><br />--|--------------------------------------------------------------------------------<br />IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= updateProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= updateProcName %>]<br />GO<br /><br />CREATE PROCEDURE [dbo].[<%= updateProcName %>]<br />(<br /><%= updateParams %><br />)<br />AS<br /> SET NOCOUNT ON<br /> <br /> UPDATE [<%= tablename %>]<br /> SET<br /><%= updateSet %><br /> WHERE <br /><%= updateWhere %><br /><% if (hasTimestamp) { %><br /> IF @@ERROR > 0<br /> BEGIN<br /> RAISERROR('Concurrency Error',16,1)<br /> END<br /><% } %><br /> RETURN @@Error<br />GO<br /><br />--|--------------------------------------------------------------------------------<br />--| [<%= deleteProcName %>] - Update Procedure Script for <%= tablename %><br />--|--------------------------------------------------------------------------------<br />IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= deleteProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= deleteProcName %>]<br />GO<br /><br />CREATE PROCEDURE [dbo].[<%= deleteProcName %>]<br />(<br /><%= deleteParams %><br />)<br />AS<br /> SET NOCOUNT ON<br /><br /> DELETE <br /> FROM [<%= tablename %>]<br /> WHERE <br /><%= deleteWhere %><br /><br /> RETURN @@Error<br />GO<br /><br /><br /><br />--|--------------------------------------------------------------------------------<br />--| [<%= selectProcName %>] - Update Procedure Script for <%= tablename %><br />--|--------------------------------------------------------------------------------<br />IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[<%= selectProcName %>]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[<%= selectProcName %>]<br />GO<br /><br />CREATE PROCEDURE [dbo].[<%= selectProcName %>]<br />(<br /><%= deleteParams %><br />)<br />AS<br /> SET NOCOUNT ON<br /><br /> SELECT * <br /> FROM [<%= tablename %>]<br /> WHERE <br /><%= deleteWhere %><br /><br /> RETURN @@Error<br />GO<br /><br /><%<br /> // Save this set of procedures to disk<br /> output.save(filename, false);<br /> buffer += output.text;<br /> output.clear();<br />}<br /><br />output.write(buffer);<br />%><br /></div>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-30439841045064105842011-10-13T11:29:00.001-07:002011-11-01T03:31:24.645-07:00How to increase session timeout on iis7Many people ask me how to increase the session time on their web site<br />so here is the answer how to do that on iis7(make all the changes from the iis view):<ol><br /><li>Application Pool => Advanced Settings => Process Model => <b>Idle Time-out</b></li><br /><li>Sites => whatever web needs to be set => ASP => Session Properties => <b>Time-out</b> <br /></li><br /><li>Sites => whatever web needs to be set => Configuration Editor => system.web/sessionState => <b>timeout</b><br /></li><br /><li>Sites => whatever web needs to be set => Configuration Editor => system.web/roleManager => <b>cookieTimeout</b><br /></ol>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-89946506900461163682011-08-13T09:49:00.000-07:002011-08-15T00:11:35.130-07:00Configure a basic build serverAutomation is power in software development
<br />the exact name is continuous integration
<br />i want to be able in one click to get latest version, build, run test and publish
<br />this click makes me feel that i have a control on my project
<br />in this post i'll show a basic configuration of build server
<br />that includes:
<br /><ol>
<br /><li>Get latest version form your source control</li>
<br /><li>Build your project</li>
<br /><li>Run your automatic testing</li>
<br /><li>Send an email notification with the status of the project (failed/success)</li>
<br /></ol>
<br />to this configuration we just have to add build trigger (schedule, on check in,...)
<br />we also have to add an email notification to get status of the project to my email inbox
<br /><br />
<br />note: to run this sample you have to include your project and your test project in the same solution
<br />you may see a sample project exactly in this structure <a href="https://sites.google.com/site/yosihaviablogfiles/files-container/SampleProject.zip" target="_blank">here</a>
<br />
<br />my build server software is <a href="http://www.jetbrains.com/teamcity/" target="_blank"">TeamCity</a>
<br />the build server configuration is very easy and includes 4 steps:
<br /><br />
<br /><span style="color:blue;font-weight:bold">step 1:<br/>-------</span>
<br /><strong>General Settings: </strong> nothing special in the first step, just supply a name for your project
<br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step1.gif"><img alt="Sample_step1" width="700px" src="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step1.gif" /></a>
<br /><br />
<br /><span style="color:blue;font-weight:bold">step 2:<br/>-------</span>
<br /><strong>Version Control Settings: </strong> create and attach a new VCS root,
<br />add checkout rule with the value of <strong>+:.</strong> (include all files)
<br />and set your checkout directory (your local directory)
<br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step2.gif"><img alt="Sample_step2" width="700px" src="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step2.gif" /></a>
<br /><br />
<br /><span style="color:blue;font-weight:bold">step 3:<br/>-------</span>
<br /><strong>Choose your build runner: </strong> this step inculde two sub-steps,
<br />choose a build runner and set your test project location
<br />the simplest runner is visual studio solution,
<br />set your solution file and set your target and configuration fields
<br /><br /> to set your test project you have to check the check box of run MSTest
<br />set the path to MSTest.exe and set the path to your project test file under
<br />List assembly files field
<br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step3.gif"><img alt="Sample_step3" width="700px" src="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step3.gif" /></a>
<br /><br />
<br /><span style="color:blue;font-weight:bold">step 4:<br/>-------</span>
<br /><strong>Build Triggering: </strong> choose your build triggering,
<br />i use a nightly scheduled build
<br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step4.gif"><img alt="Sample_step4" width="700px" src="https://sites.google.com/site/yosihaviablogfiles/files-container/Sample_step4.gif" /></a>
<br /><br />
<br />that's all now you have a build server!
<br />just set your email notification in the project settings
<br />a future work will be project publish with web config transforms
<br />i hope i won't be too lazy and publish a post on itYosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-71121485948610472252011-07-16T04:20:00.000-07:002011-07-24T23:37:33.263-07:00My Branching and Merging StrategyHi,<br />I would to share with you my way to the best practices for development version management<br />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<br /><br />my way is based on two important rules:<br /><ol><li><u>Production environment</u> must be equal to the <u>main development environment</u> for enabling production bug fixes over the iteration development<br /></li><br /><li>The <u>iteration development</u> will be only in the <u>branch development environment</u><br /></li><br /></ol><br />I'll explain it by a simple scenario as yo can see in the chart below:<br /><br /><img alt="chart" src="https://sites.google.com/site/yosihaviablogfiles/files-container/cc2.gif" /><br /><br /><br /><img alt="legend" src="https://sites.google.com/site/yosihaviablogfiles/files-container/cc3.gif" /><div>So, the scenario is:<br />1. create a branch development version from the main development version, this action occurred only once<br />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<br />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<br />4. we can update the production environment from the branch development version<br />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</div><br />from this step we have to repeat steps 2-5 for each development iteration<br /><br />one important tip:<br />when making the branch action, don't overwrite the configuration files, keep the target versionYosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-6285421273706247882011-07-16T04:17:00.000-07:002011-10-13T20:49:53.916-07:00Monitor your system for freeHi, I would like to introduce you a very nice system monitoring solution called<br /><a target="_blank" href="http://polymon.codeplex.com/">Polymon</a>. Polymon is an easy to use software that made up of three primary components:<ul><li>A <i>SQL Server database</i> to store monitor statuses, alerts and general settings.</li><br /><li>A windows service (<i>PolyMon Executive</i>) that runs monitors on a periodic basis,<br> logs results to the database and sends out email notifications.</li><br /><li>A management/monitoring front-end (<i>PolyMon Manager</i>) that is used to manage<br> general settings, monitor definitions, operators, alert rules, etc. and analyze<br> historical trends (both monitor counters and statuses). </li></ul><br />To start using this tool you have to download the latest setup file from <a href="http://polymon.codeplex.com/" target="_blank">polymon.codeplex.com</a> 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:<br /><ul><li><a href="#Disk Monitor"><b>Disk Monitor</b></a> - use this monitor type in case that you want to monitor the remaining free space in your system</li><br /><li><a href="#File Monitor"><b>File Monitor</b></a> - use this monitor type in case that you want to monitor the files count on specific directory</li><br /><li><a href="#MSMQ Monitor"><b>MSMQ Monitor</b></a> - 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</li><br /><li><a href="#Ping Monitor"><b>Ping Monitor</b></a> - use this monitor type in case that you want to monitor the system health by a ping request</li><br /><li><a href="#SQL Monitor"><b>SQL Monitor</b></a> - use this monitor type in case that you want to monitor your sql server datatbase by a structed query</li><br /><li><a href="#Service Monitor"><b>Service Monitor</b></a> - use this monitor type in case that you want to monitor your window service and check if it is still running</li><br /><li><a href="#URL Monitor"><b>URL Monitor</b></a> - use this monitor type in case that you want to monitor the a url and to make a content check on its response</li><br /></ul><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="Disk Monitor">Disk Monitor:</a></span><br/><br/> After you have selected Disk Monitor as the type of your monitor<br />you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Select the hard disk drive to monitor</li><br /> <li>Set the free space remining for the warning message</li><br /> <li>Set the free space remining for the failed message</li><br /></ol><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_diskFull_2.JPG"><br /> <img border="0" width="700px" alt='polymon_diskFull' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_diskFull_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="File Monitor">File Monitor:</a></span><br/><br/> After you have selected File Monitor as the type of your monitor<br />you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Select the target directory to monitor</li><br /> <li>Set the search filter, probably it will be *.[file_extension]</li><br /> <li>Set the file count for the warning message</li><br /> <li>Set the file count for the failed message</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_filesNo_2.JPG"><img border="0" width="700px" alt='polymon_filesNo' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_filesNo_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name ="MSMQ Monitor">MSMQ Monitor:</a></span><br/><br/> After you have selected Performence Monitor as the type of your monitor<br />and select <i>MSMQ Service</i> as the category and select <i>Total messages in all queues</i> as the counter, then you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Set the number of messages for the warning message</li><br /> <li>Set the number of messages for the failed message</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_MSMQ_2.JPG"><img border="0" width="700px" alt='polymon_MSMQ' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_MSMQ_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="Ping Monitor">Ping Monitor:</a></span><br/><br/> After you have selected Ping Monitor as the type of your monitor<br /> you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Set the ip as the destination of the ping request</li><br /> <li>Set the number of tries and the number of failures</li><br /> <li>Set the timeout for the request</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Ping_2.JPG"><img border="0" width="700px" alt='polymon_Ping' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Ping_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="SQL Monitor">SQL Monitor:</a></span><br/><br/> After you have selected SQL Monitor as the type of your monitor<br /> and wrote a stored procedure in this <a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Sql2.txt">format</a> you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Set the connection string in setting xml</li><br /> <li>Set the stored procedure name in setting xml</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_SQL1_2.JPG"><img border="0" width="700px" alt='polymon_SQL1' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_SQL1_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="Service Monitor">Service Monitor:</a></span><br/><br/> After you have selected Service Monitor as the type of your monitor<br /> you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Set the host where the service is running</li><br /> <li>Set the service name to monitor</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Srv_2.JPG"><img border="0" width="700px" alt='polymon_Srv' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Srv_2.JPG' /><br /></a><br /><br /><br /><br /><br /><span style="color: blue; font-weight: bold;border-bottom:solid 1px blue"><a name="URL Monitor">URL Monitor:</a></span><br/><br/> After you have selected URL Monitor as the type of your monitor<br /> you have to:<br /><ol style="margin-bottom:0px"><br /> <li>Set url to monitor</li><br /> <li>Set the request timeout</li><br /> <li>Set the content to check on the response text</li><br /></ol><br /><a target="_blank" href="https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Url_2.JPG"><img border="0" width="700px" alt='polymon_Url' src='https://sites.google.com/site/yosihaviablogfiles/files-container/polymon_Url_2.JPG' /><br /></a>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-51327788135376588232010-10-20T13:51:00.001-07:002011-03-10T12:49:01.451-08:00Using jquery selectors on server side(C#)Something that i have been looking for a long time<br />is to use jquery selectors on the server side.<br />if found a great solution at <b>fizzler project</b><br />fizzler is .NET CSS Selector Engine and you can download it from <a href='http://code.google.com/p/fizzler/' target='_blank'>here</a>.<br />from fizzler site:<br /><span style='font-style: italic;'>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<br /></span><br />all you have to is to download fizzler package<br />and add reference to this dll files:<br />- Fizzler.Systems.HtmlAgilityPack.dll<br />- Fizzler.Systems.XmlNodeQuery.dll<br />- HtmlAgilityPack.dll<br /><br />here you can see a useful samples:<br /><pre class="brush: js;"><br />HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();<br />html.LoadHtml(<br />@"<html><br /><head></head> <br /><body><br /><div id='content'><br /><a target='_blank' href='http://yosi-havia.blogspot.com' class='FirstName'>Yosi</a> <br /><a href='http://yosi-havia.blogspot.com' class='LastName'>Havia</a><br /></div> <br /></body> <br /></html>");<br />HtmlNode document = html.DocumentNode;<br /><br />//@@@ get all elements with content id in html(result: 1 element)<br />IEnumerable<HtmlNode> list1 = document.QuerySelectorAll("#content");<br />List<HtmlNode> lst1 = list1.ToList<HtmlNode>();<br /><br />//@@@ get all elements with FirstName class name in html(result: 1 element)<br />IEnumerable<HtmlNode> list2 = document.QuerySelectorAll(".FirstName");<br />List<HtmlNode> lst2 = list2.ToList<HtmlNode>();<br /><br />//@@@ get all anchor tags in html(result: 2 elements)<br />IEnumerable<HtmlNode> list3 = document.QuerySelectorAll("a");<br />List<HtmlNode> lst3 = list3.ToList<HtmlNode>();<br /><br />//@@@ get all elements in html(result: 6 elements)<br />IEnumerable<HtmlNode> list4 = document.QuerySelectorAll("*");<br />List<HtmlNode> lst4 = list4.ToList<HtmlNode>();<br /><br />//@@@ get element with attribue name 'target' that starts with '_bl' in html(result: 1 element)<br />IEnumerable<HtmlNode> list5 = document.QuerySelectorAll("a[target^='_bl']");<br />List<HtmlNode> lst5 = list5.ToList<HtmlNode>();</pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-25310880492130214152010-06-19T02:42:00.000-07:002010-06-19T03:09:39.382-07:00c# window service Debugging - the best way!Very intresting and complicated issue is how to debug c# window service,<br />i saw many solutions for that but no one of them made me satisfied.<br /><br />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.<br /><br />you can see the macro installation instructions in this <a href ='http://yosi-havia.blogspot.com/2010/03/create-attach-to-process-shortcut-in-vs.html'>post</a> <br />with a few changes:<br /><ul><li>use this files in step 2<br />- <a href='http://sites.google.com/site/yosihaviablogfiles/attachservice-1/Attachservice.txt'>Attachservice.txt</a><br />- <a href='http://sites.google.com/site/yosihaviablogfiles/attachservice-1/DetachService.txt'>DetachService.txt</a><br /></li><br /><li>select a different shortcut in step 6<br /></li><br /></ul>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-37015298218637020442010-03-16T13:51:00.000-07:002010-03-27T13:08:01.536-07:00Create attach to process shortcut in VS 2008Tools -> Attach to Process... -> wait for the dialog -> < select the process > -> press on attach<br />who has the time and the patience to follow this step every time we want to debug an <b>internt application</b>.<br />I'll show u how to attach to process in one shortcut press.<br />for generate the shortcut, follow the steps below:<br /><ol><br /><li>Open Visual studio</li><br /><li>Press Alt+F11 to open MyMacros</li><br /><li>Right click on MyMacros-> Add-> Add existing item and browse to this <a href='http://sites.google.com/site/yosihaviablogfiles/attachtoptocess/AttachingToProcesses.txt'>file</a>(change the file extension to .vb)</li><br /><li>Now, we have make a shortcut key to this macro, you should go to Tools -> Options and choose Environment -> Keyboard pane</li><br /><li>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)</li><br /><li>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)</li><br /><li>Press on Assign button, and ok, that's all, we finished</li><br /></ol><br /><img src='http://sites.google.com/site/yosihaviablogfiles/attachtoptocess/att.gif'/>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com1tag:blogger.com,1999:blog-7533700873371513482.post-6324855652904058952010-02-12T13:21:00.000-08:002010-02-12T13:59:23.764-08:00Create secure form without captchaUsually when we want to create a secure form that computer programs cannot pass we use the captcha program.<br />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.<br />in the idea that i'll show in this post the user cannot notice in any difference from unsecured form.<br />the steps for the very simple solution is<br /><br />1. generate a random names to inputs in the form<br />2. save the names in the session collection at the server side<br />3. after the user submits the forn, take the inputs names fron rhe session<br />4. the the inputs values from the request collection with the key names from the session<br /><span style='color:blue'><br />take a look at this simple example at asp .net but it will work in every server side language:<br />---------------------------------------------------------------------------------------<br />the server side code<br /></span><pre><br />public partial class _Default : System.Web.UI.Page <br />{<br /> public string UserNameKey;<br /> public string PasswordKey;<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Session["UserNameKey"] = UserNameKey = Guid.NewGuid().ToString();<br /> Session["PasswordKey"] = PasswordKey = Guid.NewGuid().ToString();<br /> }<br /> }<br /> protected void lnkSend_Click(object sender, EventArgs e)<br /> {<br /> if (Session["UserNameKey"] != null<br /> && Session["PasswordKey"] != null)<br /> {<br /> string UserNameValue = Request[Session["UserNameKey"].ToString()];<br /> string PasswordValue = Request[Session["PasswordKey"].ToString()];<br /> }<br /> }<br />}<br /></pre><br /><span style='color:blue'><br />the html code<br /></span><pre><br /><html><br /> <head runat="server"><br /> <title>Untitled Page</title><br /> </head><br /> <body><br /> <form id="form1" runat="server"><br /> User name: <input type="text" name="<%=UserNameKey%>" /><br /> <br /><br /> Password: <input type="password" name="<%=PasswordKey%>" /><br /> <br /><br /> <asp:LinkButton ID="lnkSend" runat="server" <br /> onclick="lnkSend_Click" >Send</asp:LinkButton><br /> </form><br /> </body><br /></html><br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-79566942198214120762009-09-14T06:07:00.000-07:002009-09-14T06:08:09.287-07:00Simple xslt exampleIn this post i'll show how 2 make a simple xsl transform.<br />In addition i'll show how to use this xsl elements:<br /><br />1. XsltArgumentList - pass arguments to the xslt<br />2. Encoding - declare the outgoing xml encoding<br />3. xsl:value-of - take the value(inner text) of node<br />4. xsl:copy-of - copy the inner xml of node<br />5. xsl:for-each - loop through same nodes<br />6. xsl:sort - sort nodes by specified node<br /><br />and in the end of the post there is a c# thread safety class to make xsl transforms<br /><br /><span style='color:blue'>so, this is the origin xml file(<b>Person.xml</b>):</span><br /><pre><br /><hPerson><br /> <Header><br /><br /> <FirstName>Yosi</FirstName><br /> <LastName>Havia</LastName><br /> <Age>30</Age><br /> <Education>BA</Education><br /> </Header><br /> <hChildren><br /> <hChild><br /> <hName>Carol</hName><br /> <hAge>13</hAge><br /> </hChild><br /> <hChild><br /> <hName>Angela</hName><br /> <hAge>15</hAge><br /> </hChild><br /> <hChild><br /> <hName>Benjamin</hName><br /> <hAge>17</hAge><br /> </hChild><br /> </hChildren><br /></hPerson><br /></pre><br /><br /><span style='color:blue'>and this is the xslt file(<b>Person.xslt</b>):</span><br /><pre style='background-color:#e8db89'><br /><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"<br /> xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"><br /> <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes" omit-xml- declaration="yes"/><br /> <xsl:param name="Gender"></xsl:param><br /> <xsl:template match="/"><br /> <Person><br /> <Gender><br /> <xsl:choose><br /> <xsl:when test="$Gender='1'"><br /> Male<br /> </xsl:when><br /> <xsl:otherwise><br /> Female<br /> </xsl:otherwise><br /> </xsl:choose><br /> </Gender><br /> <xsl:copy-of select="/hPerson/Header"/><br /> <Data><br /> <Children><br /> <xsl:for-each select="/hPerson/hChildren/hChild"><br /> <xsl:sort select="hName" /><br /> <Child><br /> <FirstName><br /> <xsl:value-of select="hName"/><br /> </FirstName><br /> <Age><br /> <xsl:value-of select="hAge"/><br /> </Age><br /> </Child><br /> </xsl:for-each><br /> </Children><br /> </Data><br /> </Person><br /> </xsl:template><br /></xsl:stylesheet><br /></pre><br /><span style='color:blue'>the output xml look like this:</span><br /><pre><br /><?xml version="1.0" encoding="UTF-8"?><br /><Person><br /> <Gender> <br /> Male<br /> </Gender><br /> <Header><br /> <FirstName>Yosi</FirstName><br /> <LastName>Havia</LastName><br /> <Age>30</Age><br /> <Education>BA</Education><br /> </Header><br /> <Data><br /> <Children><br /> <Child><br /> <FirstName>Angela</FirstName><br /> <Age>15</Age><br /> </Child><br /> <Child><br /> <FirstName>Benjamin</FirstName><br /> <Age>17</Age><br /> </Child><br /> <Child><br /> <FirstName>Carol</FirstName><br /> <Age>13</Age><br /> </Child><br /> </Children><br /> </Data><br /></Person><br /></pre><br /><span style='color:blue'>this is a thread safety c# class to make xsl transforms</span><br /><pre><br />using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Xml;<br />using System.Xml.XPath;<br />using System.Xml.Xsl;<br /><br />namespace XSLT<br />{<br /> class XsltObj<br /> {<br /> protected static XslCompiledTransform _oXslTransform;<br /> protected static object _oSyncXsl = new object();<br /> public string FormatXmlWrapper(string sEncoding, XsltArgumentList <br /> oXsltArgumentList,XmlDocument oOriginXmlDoc, string sXslPath)<br /> {<br /> string sRetVal = null;<br /> if (_oXslTransform == null)<br /> {<br /> LoadXslWrapper(sXslPath, ref _oXslTransform, ref _oSyncXsl);<br /> }<br /> //@@@ make the transform<br /> try<br /> {<br /> sRetVal = TransformData(sEncoding, _oXslTransform, oOriginXmlDoc, <br /> oXsltArgumentList);<br /> }<br /> catch (Exception ex)<br /> {<br /> throw ex;<br /> }<br /> return sRetVal;<br /> }<br /> protected void LoadXslWrapper(string sXslPath, <br /> ref XslCompiledTransform oXslTransform, ref object oSyncXsl)<br /> {<br /> lock (oSyncXsl)<br /> {<br /> if (oXslTransform == null)<br /> {<br /> XslCompiledTransform oTempXslTransform = <br /> new XslCompiledTransform();<br /> //@@@ get the xml path from configuration<br /> LoadXsl(sXslPath, ref oTempXslTransform);<br /> oXslTransform = oTempXslTransform;<br /> }<br /> }<br /> }<br /> protected void LoadXsl(string sXslPath, ref XslCompiledTransform <br /> oXslCompiledTransform)<br /> {<br /> //@@@ load the xsl document(only once)<br /> XmlDocument xslDocument = new XmlDocument();<br /> XmlUrlResolver urlResolver = new XmlUrlResolver();<br /> urlResolver.Credentials = System.Net.CredentialCache.DefaultCredentials;<br /> xslDocument.XmlResolver = urlResolver;<br /> try<br /> {<br /> //@@@ load the xsl document<br /> xslDocument.Load(sXslPath);<br /> XPathNavigator oXPathNavigator = xslDocument.CreateNavigator();<br /> oXslCompiledTransform.Load(oXPathNavigator, <br /> XsltSettings.TrustedXslt, urlResolver);<br /> }<br /> catch (Exception ex)<br /> {<br /> throw ex;<br /> }<br /> }<br /> protected string TransformData(string sEncoding, XslCompiledTransform <br /> oXslTransform, XmlDocument xmlDocument, XsltArgumentList argumentList)<br /> {<br /> StringBuilder sb = new StringBuilder();<br /> string sDeclaration;<br /> //@@@ decide the xml declaration up to the Encoding<br /> if (string.IsNullOrEmpty(sEncoding))<br /> sDeclaration = "version=\"1.0\"";<br /> else<br /> sDeclaration = "version=\"1.0\" encoding=\"" + sEncoding + "\"";<br /> //@@@ make the xsl Transform<br /> using (XmlWriter output = XmlWriter.Create(sb))<br /> {<br /> output.WriteProcessingInstruction("xml", sDeclaration);<br /> XPathNavigator oXPathNavigator = xmlDocument.CreateNavigator();<br /> oXslTransform.Transform(oXPathNavigator, argumentList, output);<br /> return sb.ToString();<br /> }<br /> }<br /> }<br />}<br /></pre><br /><span style='color:blue'>to activate this object use this code:</span><br /><pre><br />static void Main(string[] args)<br />{<br /> XsltObj oXsltObj = new XsltObj();<br /> XsltArgumentList oXsltArgumentList = GetXsltArguments();<br /> XmlDocument oXmlDocument = new XmlDocument();<br /> string sXmlPath = @"Person.xml";<br /> string sXslPath = @"Person.xslt";<br /> oXmlDocument.Load(sXmlPath);<br /> string sXml = oXsltObj.FormatXmlWrapper("UTF-8", oXsltArgumentList, <br /> oXmlDocument, sXslPath);<br />}<br />protected static XsltArgumentList GetXsltArguments()<br />{<br /> //@@@ create the arguments for the xsl<br /> XsltArgumentList list = new XsltArgumentList();<br /> list.AddParam("Gender", string.Empty, "1");<br /> return list;<br />}<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-44780948377167608772009-08-19T07:40:00.001-07:002009-08-21T13:54:11.659-07:00force download of remote fileMany times we want 2 enable 2 users to download files from our web site<br />just put this function in the Page_Load function and then the users will be enable to download <b>remote</b> files from any web site (note that the function parameter is a virtual path!):<br /><pre><br />private void forceDownloadRemoteFile(string sFileVirtualPath)<br />{<br /> string sFileName = System.IO.Path.GetFileName(sFileVirtualPath);<br /> WebClient oWebClient = new WebClient();<br /> MemoryStream oMemoryStream;<br /> try<br /> {<br /> byte[] bytes = oWebClient.DownloadData(sFileVirtualPath);<br /> oMemoryStream = new MemoryStream(bytes);<br /> }<br /> finally<br /> {<br /> oWebClient.Dispose();<br /> }<br /> BinaryReader oBinaryReader = new BinaryReader(oMemoryStream);<br /> Response.Clear();<br /> Response.ContentType = "application/octet-stream";<br /> Response.AddHeader("content-disposition", <br /> string.Format("attachment;filename={0}", sFileName));<br /> Response.BinaryWrite(oBinaryReader.ReadBytes((int)oMemoryStream.Length));<br /><br /> oBinaryReader.Close();<br /><br /> Response.Flush();<br /> Response.End();<br />}<br /></pre><br />To execute this function u can use this code:<br /><pre><br />protected void Page_Load(object sender, EventArgs e)<br />{<br /> string sFileVirtualPath = @"http://localhost/TryWebSite/TextFile.txt";<br /> forceDownloadRemoteFile(sFileVirtualPath);<br />}<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-62445228648549414372009-08-08T02:44:00.000-07:002009-08-08T04:12:04.268-07:00How to transform between object and xml in c#Hi,<br />Many times we need 2 make transforms object to xml and transform xml to object.<br />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: <br /><br /><br /><span style='color:blue'>let's say that we have <b>RootData</b> class:</span><br /><pre><br />public class RootData<br />{<br /> public HeaderElement Header;<br /> public List<Subject> SubjectsList;<br />}<br />public class HeaderElement<br />{<br /> public int DataType;<br />}<br />public class Subject<br />{<br /> public string SubjectName;<br /> public int SubjectID;<br /> public int SubjectType;<br />}<br /></pre><br /><span style='color:blue'>and we need to make transforms with this xml:</span><br /><pre><br /><?xml version="1.0" encoding="utf-8"?><br /><RootData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <br />xmlns:xsd="http://www.w3.org/2001/XMLSchema"><br /> <Header><br /> <DataType>1</DataType><br /> </Header><br /> <SubjectsList><br /> <Subject><br /> <SubjectName>Name1</SubjectName><br /> <SubjectID>1</SubjectID><br /> <SubjectType>1</SubjectType><br /> </Subject><br /> <Subject><br /> <SubjectName>Name2</SubjectName><br /> <SubjectID>2</SubjectID><br /> <SubjectType>2</SubjectType><br /> </Subject><br /> <Subject><br /> <SubjectName>Name3</SubjectName><br /> <SubjectID>3</SubjectID><br /> <SubjectType>3</SubjectType><br /> </Subject><br /> </SubjectsList><br /></RootData><br /></pre><br /><br /><span style='color:blue'>The function 2 make <b>transform from object to xml</b> is:</span><br /><pre><br />public string SerializeObject(Type oType, object oRootData)<br />{<br /> //@@@ Create xml from the object<br /> MemoryStream oMemoryStream = null;<br /> XmlTextWriter oXmlTextWriter = null;<br /> string sXml = null;<br /> try<br /> {<br /> oMemoryStream = new MemoryStream();<br /> XmlSerializer oXmlSerializer = new XmlSerializer(oType);<br /> oXmlTextWriter = new XmlTextWriter(oMemoryStream, Encoding.UTF8);<br /> oXmlSerializer.Serialize(oXmlTextWriter, oRootData);<br /> oMemoryStream = (MemoryStream)oXmlTextWriter.BaseStream;<br /> UTF8Encoding oUTF8Encoding = new UTF8Encoding();<br /> sXml = oUTF8Encoding.GetString(oMemoryStream.ToArray());<br /> }<br /> catch (Exception)<br /> {<br /> throw;<br /> }<br /> finally<br /> {<br /> if (oMemoryStream != null)<br /> oMemoryStream.Close();<br /> if (oXmlTextWriter != null)<br /> oXmlTextWriter.Close();<br /> }<br /> return sXml;<br />}<br /></pre><br /><span style='color:blue'>The function 2 make <b>transform from xml to object</b> is:</span><br /><pre><br />public object DeserializeObject(Type oType, string sXml)<br />{<br /> //@@@ Create object from the xml<br /> MemoryStream oMemoryStream = null;<br /> object oRootData = null;<br /> try<br /> {<br /> XmlSerializer oXmlSerializer = new XmlSerializer(oType);<br /> UTF8Encoding oUTF8Encoding = new UTF8Encoding();<br /> Byte[] Bytes = oUTF8Encoding.GetBytes(sXml);<br /> oMemoryStream = new MemoryStream(Bytes);<br /> oRootData = oXmlSerializer.Deserialize(oMemoryStream);<br /> }<br /> catch (Exception)<br /> {<br /> throw;<br /> }<br /> finally<br /> {<br /> if (oMemoryStream != null)<br /> oMemoryStream.Close();<br /> }<br /> return oRootData;<br />}<br /></pre><br /><span style='color:blue'>Before u run this example, u can fill your object with this function:</span><br /><pre><br />public RootData CreateData()<br />{<br /> RootData oRootData = new RootData();<br /> HeaderElement oHeaderElement = new HeaderElement();<br /> oHeaderElement.DataType = 1;<br /> oRootData.Header = oHeaderElement;<br /> <br /> Subject oSubject1 = new Subject();<br /> oSubject1.SubjectID = 1;<br /> oSubject1.SubjectName = "Name1";<br /> oSubject1.SubjectType = 1;<br /> <br /> Subject oSubject2 = new Subject();<br /> oSubject2.SubjectID = 2;<br /> oSubject2.SubjectName = "Name2";<br /> oSubject2.SubjectType = 2;<br /> <br /> Subject oSubject3 = new Subject();<br /> oSubject3.SubjectID = 3;<br /> oSubject3.SubjectName = "Name3";<br /> oSubject3.SubjectType = 3;<br /> <br /> List<Subject> Subjects = new List<Subject>();<br /> Subjects.Add(oSubject1);<br /> Subjects.Add(oSubject2);<br /> Subjects.Add(oSubject3);<br /> <br /> oRootData.SubjectsList = Subjects;<br /> return oRootData;<br />}<br /></pre><br /><span style='color:blue'>And run this code to execute the transform:</span><br /><pre><br />RootData oRootData = CreateData();<br />string sXml = SerializeObject(typeof(RootData), oRootData);<br />oRootData = (RootData)DeserializeObject(typeof(RootData), sXml);<br /></pre><br /><br />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):<br /><ul><br /><li>[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 </li><br /><li>[XmlElement(("<Xml Node Name>"), IsNullable = false)] - says that if the data member value is null it will not appear in the transformed xml</li><br /><li>[XmlAttribute] - use it when u want that the data member output will be xml attribute and not xml node</li><br /></ul>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com2tag:blogger.com,1999:blog-7533700873371513482.post-41879570577381898092009-07-25T09:02:00.000-07:002009-07-25T09:27:49.937-07:00How to identify user's country by ipIn a 4 steps u can identify the user's country<br />u will discover that it is a very easy assignment <br /><br /><b>step 1:</b><br />-------<br />Download the txt file from <a target='_blank' href='http://sites.google.com/site/yosihaviablogfiles/files-container/ip_country2.txt'>here</a>, that represent the ip ranges of each country. when u save this file change his extension to csv.<br /><br /><b>step 2:</b><br />-------<br />Import the csv file into your db and create table with the name [ip-to-country].<br /><br /><b>step 3:</b><br />-------<br />By taking the user's IP with Request.UserHostAddress convert this string to uint by this function:<br /><pre><br />public uint IPAddressToLongBackwards(string IPAddr)<br />{<br /> System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);<br /> byte[] byteIP = oIP.GetAddressBytes();<br /><br /> uint ip = (uint)byteIP[0] << 24;<br /> ip += (uint)byteIP[1] << 16;<br /> ip += (uint)byteIP[2] << 8;<br /> ip += (uint)byteIP[3];<br /><br /> return ip;<br />}<br /></pre><br /><br /><b>step 4:</b><br />-------<br />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):<br /><pre><br />SELECT countryCode2<br />from [ip-to-country]<br />where ipFrom <= @ip <br />and ipTo >= @ip<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com3tag:blogger.com,1999:blog-7533700873371513482.post-13332945873832066802009-05-24T12:18:00.000-07:002009-05-24T12:42:00.405-07:00ContainsKey problemHi,<br />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!<br />so, if u have same key values in the Dictionary and in your test object u will get negative answer.<br />the solution is 2 override Equals and GetHashCode functions:<br /><br /><pre><br /><span class='greenTxt'>//@@@ I have Dictionary with Key_Event5 object as the key</span><br />Dictionary<Key_Event5, Event5_Employment> dictEmployment;<br /><span class='greenTxt'>//@@@ 4 support ContainsKey function compare by value, i'll implement Key_Event5 on this way:</span><br />public class Key_Event5<br />{<br /> public int iFormID { get; set; }<br /> public int iEmploymentCode { get; set; }<br /> public Key_Event5(int iFormID, int iEmploymentCode)<br /> {<br /> this.iFormID = iFormID;<br /> this.iEmploymentCode = iEmploymentCode;<br /> }<br /><span style='color:blue'><br /> public override bool Equals(object obj)<br /> {<br /> Key_Event5 oKey_Event5 = obj as Key_Event5;<br /> if (oKey_Event5 == null)<br /> return false;<br /> <span class='greenTxt'>//@@@ Compare by iFormID and iEmploymentCode</span><br /> return Equals(iFormID, oKey_Event5.iFormID) <br /> && Equals(iEmploymentCode, oKey_Event5.iEmploymentCode);<br /><br /> }<br /> public override int GetHashCode()<br /> {<br /> return iFormID.GetHashCode() ^ iEmploymentCode.GetHashCode();<br /> }</span><br />}<br /><span class='greenTxt'>//@@@ And now this line will work</span> <br />dictEmployment.ContainsKey(oKey_Event5)<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-57900137505296500762009-05-24T11:19:00.000-07:002009-05-24T12:02:00.611-07:00Simple XPath ExamplesHi,<br />In this post i'll show some simple(but useful) XPath Examples<br />let's say that i have this xml file named 'Persons.xml':<br /><br /><pre><br /><?xml version='1.0'?><br /><br /><Persons><br /><br /> <Person Height="180"><br /><br /> <FullName>Yosi Havia</FullName><br /><br /> <Age>18</Age><br /><br /> </Person><br /><br /> <Person Height="177"><br /><br /> <FullName>Yosi Cohen</FullName><br /><br /> <Age>22</Age><br /><br /> </Person><br /><br /> <Person Height="169"><br /><br /> <FullName>Itay Cohen</FullName><br /><br /> <Age>32</Age><br /><br /> </Person><br /><br /></Persons><br /><br /></pre><br /><b>so, let's talk code lines</b>:<br /><br /><pre><br /><span class='greenTxt'>//@@@ Select all the persons in 18 age</span><br />XmlNodeList oXmlNodeList = <br />XmlPersons.SelectNodes("/Persons/Person[Age = '" + 18 + "']");<br /></pre><br /><pre><br /><span class='greenTxt'>//@@@ Select all the persons with age greater than 17</span><br />XmlNodeList oXmlNodeList = <br />XmlPersons.SelectNodes("/Persons/Person[Age > '" + 17 + "']");<br /></pre><br /><pre><br /><span class='greenTxt'>//@@@ Select all the persons that contains Yosi in their names</span><br />XmlNodeList oXmlNodeList = <br />XmlPersons.SelectNodes("/Persons/Person/FullName[contains(.,'" + "Yosi" + "')]");<br /></pre><br /><pre><br /><span class='greenTxt'>//@@@ Select all the persons with 180 height(attribute)</span><br />XmlNodeList oXmlNodeList = <br />XmlPersons.SelectNodes("/Persons/Person[@Height = '" + "180" + "']");<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com4tag:blogger.com,1999:blog-7533700873371513482.post-21999018702300209272009-05-09T06:49:00.000-07:002009-05-24T12:12:49.123-07:00How to merge 2 XmlDocumentsHi,<br />In this post i'll show u how 2 merge 2 xml documents<br />let's say that i have 2 xml documents,<br /><br /><b>Persons.xml</b><br /><pre><br /><?xml version='1.0'?><br /><br /><Persons><br /><br /> <Person Height="180"><br /><br /> <FullName>Yosi Havia</FullName><br /><br /> <Age>18</Age><br /><br /> </Person><br /><br /> <Person Height="177"><br /><br /> <FullName>Yosi Cohen</FullName><br /><br /> <Age>22</Age><br /><br /> </Person><br /><br /> <Person Height="169"><br /><br /> <FullName>Itay Cohen</FullName><br /><br /> <Age>32</Age><br /><br /> </Person><br /><br /></Persons><br /><br /></pre><br /><br />and <b>Persons2.xml</b><br /><pre><br /><?xml version='1.0'?><br /><br /><Persons><br /><br /> <Person Height="175"><br /><br /> <FullName>Yosi Havia</FullName><br /><br /> <Age>15</Age><br /><br /> </Person><br /><br /></Persons><br /><br /></pre><br /><br />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.<br />this code lines make this assigment(with help of my last post <a target='_blank' href='http://yosi-havia.blogspot.com/2009/05/simple-xpath-examples.html'>Simple XPath Examples </a> ):<br /><pre><br />XmlDocument XmlPersons1 = new XmlDocument();<br />XmlPersons1.Load(@"Persons.xml");<br /> <br />XmlDocument XmlPersons2 = new XmlDocument();<br />XmlPersons2.Load(@"Persons2.xml");<br /> <br />XmlNode oXmlNewData = XmlPersons2.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");<br /> XmlNode targetNode = XmlPersons1.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");<br /><span class='greenTxt'>//@@@ Add the node from XmlPersons2.xml to XmlPersons.xml</span><br />XmlNode sourceNode = XmlPersons1.ImportNode(oXmlNewData, true);<br /><span class='greenTxt'>//@@@ Replace the original node</span> <br />XmlPersons1.DocumentElement.ReplaceChild(sourceNode, targetNode);<br /></pre><br />and u can c the result here:<br /><pre><br /><?xml version="1.0"?><br /><br /><Persons><br /><br /> <Person Height="<span style='color:blue'>175</span>"><br /><br /> <FullName>Yosi Havia</FullName><br /><br /> <Age><span style='color:blue'>15</span></Age><br /><br /> </Person><br /><br /> <Person Height="177"><br /><br /> <FullName>Yosi Cohen</FullName><br /><br /> <Age>22</Age><br /><br /> </Person><br /><br /> <Person Height="169"><br /><br /> <FullName>Itay Cohen</FullName><br /><br /> <Age>32</Age><br /><br /> </Person><br /><br /></Persons><br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com2tag:blogger.com,1999:blog-7533700873371513482.post-72942112796724197722009-05-06T09:43:00.000-07:002009-05-06T09:49:49.441-07:00Performence check in c# with StopwatchHi,<br />System.Diagnostics has a very nice object called <b>Stopwatch</b> <br />i show here my very easy and simple example 4 making performence check: <br /><pre><br />Stopwatch oStopwatch = new Stopwatch();<br />oStopwatch.Start();<br /><span class="greenTxt">//@@@ Start of code to make the performence check</span><br />Thread.Sleep(3000);<br /><span class="greenTxt">//@@@ End of code to make the performence check</span><br />oStopwatch.Stop();<br />TimeSpan oTimeSpan = oStopwatch.Elapsed;<br />Console.WriteLine(oTimeSpan.ToString());<br /></pre><br /><br />the output of this code was:<br /><pre><br />00:00:02.9994520<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-30143067130252844582009-04-24T01:52:00.000-07:002009-05-06T07:40:23.630-07:00Don't use XmlDocument use XmlTextReader insteadHi,<br />I had an assignment to read a 200 MB xml file<br />i dont think that XmlDocument can help me here...<br />so i found the XmlTextReader object that made a great job<br />and from this moment i always use XmlTextReader to read<br />xml file content, so here is my example:<br /><br />lets say that i want to read this Test.xml file:<br /><br /><pre><br /><?xml version="1.0" encoding="utf-8" ?><br /><br /><RootNode><br /><br /> <Child><br /><br /> <Item Att="1">A</Item><br /><br /> <Item Att="2">B</Item><br /><br /> </Child><br /><br /> <Child><br /><br /> <Item Att="3">C</Item><br /><br /> <Item Att="4">D</Item><br /><br /> </Child><br /><br /></RootNode><br /><br /></pre><br /><br />and this function read all the attributes and content<br />of the Item node in the xml:<br /><br /><pre><br />public void ReadXml()<br />{<br /> int iCodepage = 862;<br /> string sAttribute, sNodeValue;<br /> string sFilePath = @"Test.xml";<br /> StreamReader oFileStream = null;<br /> XmlTextReader reader = null;<br /> <span class="greenTxt">//@@@ Check if the file exists</span><br /> if (!File.Exists(sFilePath))<br /> return;<br /><br /> <span class="greenTxt">//@@@ Get the file as XmlTextReader</span><br /> oFileStream =<br /> new StreamReader(sFilePath, Encoding.GetEncoding(iCodepage));<br /> reader = new XmlTextReader(oFileStream);<br /><br /> <span class="greenTxt">//@@@ Loop through all the file</span><br /> while (reader.Read())<br /> {<br /> <span class="greenTxt">//@@@ If we in Item node</span><br /> if (reader.Name.Equals("Item") &&<br /> (reader.NodeType == XmlNodeType.Element))<br /> {<br /> <span class="greenTxt">//@@@ Get the Attribute (Att) value</span><br /> reader.MoveToAttribute("Att");<br /> sAttribute = reader.Value;<br /> Console.WriteLine(sAttribute);<br /> <span class="greenTxt">//@@@ Get the node value</span><br /> reader.MoveToElement();<br /> sNodeValue = reader.ReadInnerXml();<br /> Console.WriteLine(sNodeValue);<br /> }<br /> }<br /> }<br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-23516133955825187392009-04-21T13:14:00.000-07:002009-04-21T13:22:14.807-07:00The perfect c# singletonHi,<br />after several tries i got the perfect thread safety c# singleton<br /><pre><br />public class DbProxy<br />{<br /> private static DbProxy _oInstance = null;<br /> private static readonly object padlock = new object();<br /> <br /> // @@@ public "consructor"<br /> public static DbProxy Instance<br /> {<br /> get<br /> {<br /> if (DbProxy._oInstance == null)<br /> {<br /> lock (padlock)<br /> {<br /> if (DbProxy._oInstance == null)<br /> {<br /> DbProxy newDB = new DbProxy();<br /> System.Threading.Thread.MemoryBarrier();<br /> DbProxy._oInstance = newDB;<br /> }<br /> }<br /> }<br /> return DbProxy._oInstance;<br /> }<br /> }<br /> // @@@ private constructor<br /> private DbProxy()<br /> {<br /><br /> }<br />}<br /><br /><br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com3tag:blogger.com,1999:blog-7533700873371513482.post-50858149492583313232009-04-13T06:17:00.000-07:002009-04-14T04:00:07.400-07:00Output Cache by the bookHi,<br />i found the best way to implement Output Cache<br />we have only 2 steps to make it:<br /><br />step 1<br />------<br />define in the Web.config some different cache profiles that u need:<br /><pre><br /><system.web><br /><br /> <caching><br /><br /> <outputCacheSettings><br /><br /> <outputCacheProfiles><br /><br /> <add name="profile1" duration="100" varyByParam="param1" /><br /><br /> <add name="profile2" duration="100" varyByParam="None" /><br /><br /> </outputCacheProfiles><br /><br /> </outputCacheSettings><br /><br /> </caching><br /><br /></system.web><br /></pre><br /><br />step 2<br />------<br />define in your pages the profile that u want to use:<br /><pre><br /><%@ OutputCache CacheProfile="profile1" %><br /></pre><br /><br />now, if we want to check if it works<br />all we have to is to make aspx page, and to play with his links<br />and check if the DateTime changed or not<br /><strong>TEST.aspx</strong><br /><pre><br /> <%@ OutputCache CacheProfile="profile1" %><br /><br /> <html xmlns="http://www.w3.org/1999/xhtml" ><br /><br /> <body><br /><br /> <form id="form1" runat="server"><br /><br /> <%= DateTime.Now.ToString() %><br /><br /><br /> <a href="?param1=1">1</a><br /><br /><br /> <a href="?param1=2">2</a><br /><br /><br /> <a href="?param1=3">3</a><br /><br /><br /> </form><br /><br /> </body><br /><br /> </html> <br /></pre><br /><br />Another small tip:<br />for disable the OutputCache(in the development environment for example) add <strong>location="None"</strong> in the appropriate profile in the web.config in this way:<br /><pre><br /><add name="profile1" duration="100" varyByParam="param1" location="None" /><br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-4946365928002194622009-04-11T09:53:00.000-07:002009-04-11T09:57:25.588-07:00A new startup - create a permanent breakpointHi,<br />with this line u can create a permanent breakpoint in c# applications:<br /><pre>System.Diagnostics.Debugger.Break();</pre><br />recomanded and very usefulYosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com0tag:blogger.com,1999:blog-7533700873371513482.post-70916176114357787982009-04-08T03:36:00.000-07:002009-04-10T12:55:58.245-07:00Send array of objects form client to serverHi,<br />with this code u can send array of object form client to server in c#<br />u have to copy the client and server code from this post<br />and use this 2 dependencies:<br />1. <a href="http://www.json.org/json2.js">JSON Code</a>(Take js file)<br />2. <a href="http://json.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=25040">Serialize Code</a>(Take dll file)<br /><br />THE SERVER CODE:<br /><pre><br />using System;<br />using System.Collections;<br />using System.Configuration;<br />using System.Data;<br />using System.Web;<br />using System.Web.Security;<br />using System.Web.UI;<br />using System.Web.UI.HtmlControls;<br />using System.Web.UI.WebControls;<br />using System.Web.UI.WebControls.WebParts;<br />using Newtonsoft.Json;<br />using System.Collections.Generic;<br /><br />public partial class tbl1 : System.Web.UI.Page<br />{<br /> public string tempPerson;<br /> public string temp_arr;<br /> public List<person> person_arr = new List< person >();<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> Person person = new Person();<br /> person.name = string.Empty;<br /> person.age = 0;<br /> string json1 = JavaScriptConvert.SerializeObject(person);<br /> tempPerson = json1;<br /> string json = JavaScriptConvert.SerializeObject(person_arr); <br /> temp_arr = json;<br /> }<br /> protected void LinkButton1_Click(object sender, EventArgs e) <br /> {<br /> person_arr = JavaScriptConvert.DeserializeObject< List< person > > <br /> (hiData.Value);<br /> }<br />}<br />public class Person<br />{<br /> public string name;<br /> public int age;<br />}<br /></pre><br /><br /><br />THE CLIENT CODE:<br /><pre><br /><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Arr.aspx.cs" Inherits="tbl1" %><br /><script src="json2.js" type="text/javascript"></script><br /><script type="text/javascript"> <br /> var arr = <%=temp_arr%>;<br /> var p1 = <%=tempPerson%>;<br /> var hiDataID = '<%=hiData.ClientID%>';<br /> function add_to_arr(name, age)<br /> {<br /> var tempP = clone(p1);<br /> tempP.name = name;<br /> tempP.age = age;<br /> arr[arr.length] = tempP;<br /> }<br /> function add2Items()<br /> {<br /> add_to_arr("name1", 1);<br /> add_to_arr("name2", 2);<br /> var g = JSON.stringify(arr);<br /> document.getElementById(hiDataID).value = g;<br /> }<br /> function clone(obj)<br /> {<br /> return JSON.parse(JSON.stringify(obj));<br /> }<br /></script><br /><form id="form1" runat="server"><br /><div><br /> <input onclick="add2Items()" type="button" value="Create Array"><br /> <input id="hiData" type="hidden" runat="server"><br /></div><br /><asp:linkbutton id="LinkButton1" onclick="LinkButton1_Click" runat="server">Send To Server</asp:linkbutton><br /></form><br /></pre>Yosi Haviahttp://www.blogger.com/profile/01342437014546015494noreply@blogger.com1