Saturday, December 20, 2008
Visual Studio 2010 CTP and Training Kit
Posted by Bairam.! at 10:37 PM 1 comments
Labels: Technology News, Visual Studio.NET
Tuesday, November 25, 2008
New certification from Microsoft 70-441
Yesterday I passed 70-441 by score of 966. Exam Details
PRO: Designing Database Solutions by Using Microsoft SQL Server 2005 exam
Here are some notes about it:
- It has 6 testlets that contains 56 questions
"Testlet is actually a scenario based set of questions, covers from 5 to 12 questions"
1- A. Datum Corporation
2- Woodgrove Bank
3- Trey Research
4- Consolidated Messenger
5- Southridge Video
6- Coho Vineyard&Winery
- Each scenario consists of sections like:
- BACKGROUND
- EXISTING ENVIRONMENT
- BUSINESS REQUIREMENTS
- TECHNICAL REQUIREMENTS
- You can view scenario sections anytime while answering questions
- Each testlet has its own time limit, which tests your design capabilities under stress
I readed the books
- MCITP-Self-Paced-Training-Kit-Exam-Designing-Database-Solutions-by SQL 2005
- MCTS-certification-Microsoft-SQL-Server-2005-Database-Essentials-Step-by-Step
- Microsoft-SQL-Server-TM-2005-Applied-Techniques-Step-by-Step
Posted by Bairam.! at 1:30 AM 0 comments
Labels: Exams and Certifications, SQL Server
Monday, November 24, 2008
Microsoft SQL Server 2005 New Features
Contents:
- Using SQL Server Configuration Manager
- Using SQL Server Surface Area Configuration
- Using Surface Area Configuration for Services And Connections
- Using Surface Area Configuration For Features
- Using Dependencies
- Using SQL Server Management Studio Templates
SQL server 2005 has many tools to help you analyze behavior, enable features, and study and enhance the performance of your server. The following sections will describe some of these tools.
1- Using SQL Server Configuration Manager
It is a Microsoft Management Console application that allows you to configure SQL Server 2005’s installed services, network configuration, and network protocols.
You can perform actions such as starting, pausing, and stopping services as well as defining the SQL Server and SQL Native Client network configuration.
Open it from
Start menu à choose All Programs à Microsoft SQL Server 2005 à Configuration Tools à SQL Server Configuration Manager
It can be used for running, stopping and restarting SQL Server services which are:
o SQL Server Integration Services
o SQL Server Full-Text Search Services
o SQL Server
o SQL Server Analysis Services
o SQL Server Reporting Services
o SQL Server BrowserSQL Server Agent
Using the SQL Server 2005 Network Configuration Node
It allows you to configure the network protocols used by each SQL Server instance by enabling or disabling the protocol.
Aliases:
Aliases are alternate names that can be used to connect to a SQL Server instance. Egypt_Server_Test will be the alias name that maps to the SQL Server instance egypt-aeid\Products , using the TCP/IP network protocol with port number 1433
2- Using SQL Server Surface Area Configuration
It is a tool that helps you enable, disable, start, or stop the features and services of your local and remote SQL Server 2005 installations. Stopping and disabling unused services allows you to reduce the surface area and makes your system more secure.
Open it from
--> Start menu --> choose All Programs --> Microsoft SQL Server 2005 --> Configuration Tools --> SQL Server Surface Area Configuration
2.1 Using Surface Area Configuration For Services And Connections
It allows you to configure the state of SQL Server services. You can stop, pause, resume, and start the SQL Server instance services. Moreover, you are able to configure whether the SQL Server instance will allow remote connections and, if so, which protocols to use
- Database Engine
- Analysis Services
- Reporting Services
- SQL Agent
- Full-Text Search
- Integration Services
- SQL Server Browser
All components have Service item for managing service settings:
Startup type : Use to configure how the service starts.
Automatic specifies that the service starts when the system starts.
Manual specifies that a user or dependent service can start the service, and that the service does not start when the system starts.
Disabled prevents the service from being started by the system, a user, or any dependent service.
Service status : Shows the status of the service.
Remote Connections for
- Database Engine
- Reporting Services
It is used to change the protocols on which SQL Server listens for incoming client connections. TCP/IP is preferred over named pipes because it requires fewer ports to be opened across the firewall
Local connections only
If selected, the Database Engine instance will only listen for shared memory connections on the local computer. Connections from remote computers will fail.
Local and remote connections
If selected, the Database Engine instance will listen for connections from the local computer and from remote computers using the selected protocols.
Using TCP/IP protocol only
If selected, the Database Engine instance listens for remote connections using TCP/IP, but not named pipes.
Using Named Pipes protocol only
If selected, the Database Engine instance listens for remote connections using named pipes, but not TCP/IP.
Using both TCP/IP and Named Pipes protocols
If selected, the Database Engine instance listens for remote connections using TCP/IP and named pipes.
2.2 Using SQL Server Surface Area Configuration for Features
It provides a single interface for enabling or disabling many Database Engine, Analysis Services, and Reporting Services features. Disabling unused features helps to secure your Microsoft SQL Server installations by reducing the SQL Server surface area.
SQL Mail, which is deprecated in favor of Database Mail, is disabled by default. Using this dialog, you can enable SQL Mail for backward compatibility.
3- Using Dependencies
Some database objects have dependencies upon other database objects. For example stored procedures may depend on objects like functions, tables, views …etcYou find dependencies by right click on any database object like tables, views, sp , fn ….etc
There are 2 types of dependencies for an object:
a- Objects that depend on
b- Objects on which
It displays a list of those objects that are dependency-tracked, on which the selected object depends.
Using SQL Server Management Studio Templates
Templates are files that contain SQL scripts to help you create objects in the database.
You can create objects such as
o Databases
o Tables
o Views
o Indexes
o Stored procedures
o Triggers
o Statistics
o Functions
Open it from
Open SQL Server Management Studio --> View Menu --> Template Explorer
Find the sql files on hard disk from
"C:\Documents and Settings\
Lets Create Stored Procedure ( New Menu )
Note: you can do the same step from the object explorer to a database, under programmability Stored Procedure, then by right click on that node
Note: the created template contains many params and names needed to renamed, you can do that by the use of wizard (Ctrl + Shift + M)
Note: if you press OK, you won’t modify the names by wizard again.
Posted by Bairam.! at 5:23 AM 0 comments
Labels: SQL Server, Technology News
Sunday, November 9, 2008
Provider Design Patterns in NET 2.0
Download ProviderDesignPattern.zip - 4.01 MB
- Introduction
- What are the benefits of the article ?
- Application Architecture
- Application Configuration
- Provider Implementation
- Restoring Database
- Debugging code
- Conclusion
- References
Introduction
Provider Design Pattern is a new pattern that Microsoft formalized in ASP.NET Whidbey. The pattern was officially named in the summer of 2002 when Microsoft was designing Whidbey's new Personalization feature.Benefits of Provider
- No need to explicitly instantiate classes. The .NET framework will automatically manage class instantiation, including re-using classes that have already been instantiated. This will greatly improve the memory management of your application.
- Switching data sources is much easier. Changing the source of data for your application from the current database to any database, whether SQL Server, Oracle, XML, or other, is a simple as replacing your existing concrete (implementer) class with a new concrete (implementer) class and inheriting from your provider class. That is all. Your presentation and business logic layers remain unchanged, thereby reducing effort required to switch data sources and the amount of regression testing required thereafter.
- Learning the Provider Design concept will make it very easy to customize built-in .NET framework providers.
For example, to create a Person provider for SQL, you create a new class SqlPersonProvider, which derives from PersonProvider. The base class of PersonProvider is ProviderBase . The ProviderBase class is used to mark implementers as a provider and forces the implementation of a required method and property common to all providers.
What are the benefits of the article ?
- Understanding the implementation of Provider Design Pattern- Understanding the implementation of 3-tier architecture application
- Understanding the application architecture
- Naming Conventions
Note: I strongly suggest that you use the exact names that I use in this document to develop your solution for the purpose of learning this concept. Once you have tested and understand how it works, then you can integrate your own naming conventions.
Application Implementation
I developed an application, Phone Book, as desktop application to describe the provider idea.The phone book application was developed with the use of 3 tier architecture as shown on application architecture.
Database objects like tables, fields and stored procedures are represented by object oriented classes, properties and methods on the provider infos of CompanyName library
The presentation layer calls the result from business logic layer and then data retrieved from database by the use of providers implemented at data access layer library.
Solution Projects [ 4 Projects]:
- BusinessLogicLayer : The business logic layer of the application
- CompanyName: it includes the global classes to all solution's projects
- DataAccessLayer: The data access layer of the application
- PhoneBookApplication: The presentation layer
Application Architecture
The following figure depicts the common tiers of a distributed application. This document distinguishes between business data and the business processes that use the data; the business process tier is discussed only where needed for clarification. Likewise, the presentation tier is discussed only where there are direct implications for the way data is represented, such as the way Microsoft® ASP.NET Web pages expose business data. Read Morethe following diagram describes the architecture of all solution's projects:
The following diagram, ERD, is the database design of phonebook
The following diagram, Use-Case diagram, describe the main functionality of the application:
Now, we can discuss the implementation of each project:
(1) Open Visual Studio 2005
1- Create Windows Application and name it PhoneBookApplication
2- Choose File Menu --> Add --> New Project and name it BusinessLogicLayer
3- Choose File Menu --> Add --> New Project and name it DataAccessLayer
4- Choose File Menu --> Add --> New Project and name it CompanyName CompanyName :
this project will include common libraries that are globally used in the development and shared objects among projects
so you will add reference for CompanyName library to all other applications.
ex. i created the provider info classes to be shared among the "BussinessLogicLayer" and "DataAccessLayer" projects
(2) Add Reference to the below DLLs for the BusinessLogicLayer and DataAccessLayer
- System.Web
- System.Configuration
- CompanyName
(4) Configuaring the App.config of the "PhoneBookApplication"
if you look to the xml elments in app.config, we define seciongroup named "PhoneBook" and added 2 sections to it which are "Person" and "Group"
<sectionGroup name="PhoneBook">
<section name="Person" type="CompanyName.PhoneBook.DataAccessLayer.SectionConfig, DataAccessLayer" />
<section name="Group" type="CompanyName.PhoneBook.DataAccessLayer.SectionConfig, DataAccessLayer" />
</sectionGroup>
then define that section group as:
<PhoneBook>
<Person>
<providers>
<add name="SqlPerson" type="CompanyName.PhoneBook.DataAccessLayer.SqlPersonProvider, DataAccessLayer"
connectionStringName="strcon" />
<add name="OraclePerson" type="CompanyName.PhoneBook.DataAccessLayer.OraclePersonProvider, DataAccessLayer"
connectionStringName="OracleConnection" />
<add name="AccessPerson" type="CompanyName.PhoneBook.DataAccessLayer.AccessPersonProvider, DataAccessLayer"
connectionStringName="AccessConnection" />
</providers>
</Person>
<Group>
<providers>
<add name="SqlGroup" type="CompanyName.PhoneBook.DataAccessLayer.SqlGroupProvider, DataAccessLayer"
connectionStringName="strcon" />
</providers>
</Group>
</PhoneBook>
then define the connection strings for data stores of "SQL, Oracle and Access"
<connectionStrings>
<add name="strcon" connectionString="Data Source=.;Initial Catalog=AhmedEid_PhoneBook;Integrated Security=True" />
<add name="OracleConnection" connectionString="oracle_connection_string" />
<add name="AccessConnection" connectionString="Access_connection_string" />
</connectionStrings>
person provider could retrieve data from SQL,Oracle or Access database.
Group provider could retrieve data from SQL only (5) Implementing DataAccessLayer Suppose PhoneBook is a midsize business and the PhoneBookApplicaion contains 2 major sections: - Person : profile management
- Groups : categorization of persons The following code reads all providers defined in your web.config. That is all you have to do to make providers information available to other classes.
using System;
using System.Configuration;
namespace CompanyName.PhoneBook.DataAccessLayer
{
public class SectionConfig : ConfigurationSection
{
[ConfigurationProperty("providers")]
public ProviderSettingsCollection Providers
{
get
{
return (ProviderSettingsCollection)base["providers"];
}
}
}
}
We need to create another class to have access to the Framework provider collection and to add our new provider(s) to the provider collection.
using System;
using System.Configuration.Provider;
namespace CompanyName.PhoneBook.DataAccessLayer
{
public class ProviderList : ProviderCollection
{
public override void Add(ProviderBase provider)
{
if (provider == null) throw new ArgumentNullException("The provider parameter cannot be null.");
base.Add(provider);
}
}
}
Create another class that will initialize the provider by the provider name.
example: initialize the Group provider for SQLGroupProvider class using provider name of "SQLGroup"
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Configuration;
using System.Configuration;
using CompanyName.PhoneBook.DataAccessLayer;
namespace CompanyName.PhoneBook.DataAccessLayer
{
public abstract class InitMember<T>
{
public static ProviderList Providers(string _providerSectionName)
{
SectionConfig qc = (SectionConfig)ConfigurationManager.GetSection(_providerSectionName);
providerCollection = new ProviderList();
// this wl instatiate PersonProvider with the class "personimpl" which inherit it
ProvidersHelper.InstantiateProviders(qc.Providers, providerCollection, typeof(T));
providerCollection.SetReadOnly();
return providerCollection;
}
private static ProviderList providerCollection;
}
}
The class takes the provider you want to initialize, i.e PersonProvider, its class and the provider name
This enum founded on CompanyName.Globals class
using that class from the Instance method of PersonProvider Class:
/// <summary>
/// This will initialize the provider and add instanse to the providers list
/// </summary>
/// <param name="_Provider"></param>
/// <returns></returns>
public static PersonProvider Instance(Globals.Providers _Provider)
{
return (DataAccessLayer.PersonProvider)DataAccessLayer.InitMember
<DataAccessLayer.PersonProvider>.Providers("PhoneBook/Person")[_Provider.ToString()];
}
This method will initialize the provider and add instance to the providers list
Now our "DataAccessLayer" project has the necessary classes for all providers to be later developed.
so we are going to develop two providers:
- PersonProvider
- GroupProvider
BaseProvider --> xxxProvider --> SQLxxxProvider xxx is the name of entity like Person, Group, ....etc Person Provider Classes:
Group Provider Classes:
Let me explain the implementation of the PersonProvider and you can create GroupProvider by yourself: first we create a class named "PersonProvider.cs"
using System;
using CompanyName.PhoneBook.Providers;
using System.Configuration.Provider;
using System.Configuration;
using System.Web.Configuration;
namespace CompanyName.PhoneBook.DataAccessLayer
{
public abstract class PersonProvider : ProviderBase
{
/// <summary>
/// This will initialize the provider and add instanse to the providers list
/// </summary>
/// <param name="_Provider"></param>
/// <returns></returns>
public static PersonProvider Instance(Globals.Providers _Provider)
{
return (DataAccessLayer.PersonProvider)DataAccessLayer.InitMember
<DataAccessLayer.PersonProvider>.Providers("PhoneBook/Person")[_Provider.ToString()];
}
/// <summary>
/// Add new person
/// </summary>
/// <param name="_info"></param>
/// <returns></returns>
public abstract bool Add(PersonInfo _info);
/// <summary>
/// Modify selected person
/// </summary>
/// <param name="_info"></param>
/// <returns></returns>
public abstract bool Modify(PersonInfo _info);
/// <summary>
/// Delete selected person
/// </summary>
/// <param name="_PersonId"></param>
/// <returns></returns>
public abstract bool Delete(int _PersonId);
/// <summary>
/// Get all personns
/// </summary>
/// <returns></returns>
public abstract PersonInfo[] Find();
/// <summary>
/// Get info of person
/// </summary>
/// <param name="_PersonId"></param>
/// <returns></returns>
public abstract PersonInfo GetInfo(int _PersonId);
/// <summary>
/// Get personns that match a given criteria
/// </summary>
/// <param name="_Searchinfo"></param>
/// <returns></returns>
public abstract PersonInfo[] Find(SearchCriteriaInfo _Searchinfo);
}
}
Instance() method : is responsible for instantiating our concrete (implementer) class (SqlGeneralProvider.cs), which has been defined within Web.config. and "PersonProvider" abstract class, which it inherits from ProviderBase and include person abstracted functions. (6)
BusinessLogicLayer
Note: It is a good idea to add a Helper class into your BusinessLogicLayer project. This way, you can expose some common functionality to all of your BusinessLogicLayer classes just by inheriting from this helper class.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace CompanyName.PhoneBook.BusinessLogicLayer
{
/// <summary>
/// You can use helper to provide common info./data needed OR to massage or add more info.
/// to your data before sending it to presentation.
/// </summary>
public abstract class Helper
{
protected static string MachineName
{
get
{
return Environment.MachineName;
}
}
}
// Add more methods/properties below
}
then define the business classes for the Person and Group providers.
Person.cs
using System;
using System.Collections.Generic;
using System.Text;
using CompanyName.PhoneBook.Providers;
using CompanyName.PhoneBook.DataAccessLayer;
namespace CompanyName.PhoneBook.BusinessLogicLayer
{
public abstract class Person : Helper
{
static PersonProvider objPersonProvider;
/// <summary>
/// Person Cnstructor
/// </summary>
//Class Constructor: will be invoked 1 time only / Appdomain
static Person()
{
objPersonProvider = PersonProvider.Instance(Globals.Providers.SqlPerson);
}
// staticed methods for person
/// <summary>
/// Add new person
/// </summary>
/// <param name="_info"></param>
/// <returns></returns>
public static bool Add(PersonInfo _info)
{
// You can use helper to provide common info./data needed OR to
// massage or add more info. to your data before sending it to
// presentation.
// Here we use helper class to get MachineName and pass it along
// with data to presentation.
return objPersonProvider.Add(_info);
}
/// <summary>
/// Modify selected person
/// </summary>
/// <param name="_info"></param>
/// <returns></returns>
public static bool Modify(PersonInfo _info)
{
return objPersonProvider.Modify(_info);
}
/// <summary>
/// Delete selected person
/// </summary>
/// <param name="_PersonId"></param>
/// <returns></returns>
public static bool Delete(int _PersonId) { return objPersonProvider.Delete(_PersonId); }
/// <summary>
/// Get all personns
/// </summary>
/// <returns></returns>
public static PersonInfo[] Find() { return objPersonProvider.Find(); }
/// <summary>
/// Get info of person
/// </summary>
/// <param name="_PersonId"></param>
/// <returns></returns>
public static PersonInfo GetInfo(int _PersonId) { return objPersonProvider.GetInfo(_PersonId); }
/// <summary>
/// Get personns that match a given criteria
/// </summary>
/// <param name="_Searchinfo"></param>
/// <returns></returns>
public static PersonInfo[] Find(SearchCriteriaInfo _Searchinfo) { return objPersonProvider.Find(_Searchinfo); }
}
}
define objPersonProvider as PersonProvider to be shared among the instances of Person class. Then initialize it on the class constructor which will be invoked for one time/ Appdomain
Person objPerson_1 = new Person(); // on class A
Person objPerson_2 = new Person(); // on class B
Person objPerson_3 = new Person(); // on class C
//Class Constructor: will be invoked 1 time only / Appdomain
static Person()
{
objPersonProvider = PersonProvider.Instance(Globals.Providers.SqlPerson);
}
The objPersonProvider will be initialized with the objPerson_1 constructor only on the class A, then other instances like objPerson_2 or objPerson_3 will use the static object objPersonProvider. you can add you business logic to every method before calling the data access provider as
public static bool Add(PersonInfo _info)
{
// Here: you can add you business logic to every method before calling the data access provider
return objPersonProvider.Add(_info);
}
PhoneBook Application
The presentation layer as desktop application for implementing the business logic to the client. <image31>
How to use the BL layer from the presentation layer ? sample code
// build the search criteria
SearchCriteriaInfo objSearchInfo = new SearchCriteriaInfo();
objSearchInfo.FilterNameBy = (Globals.FilterNameBy)this.cboName.SelectedValue;
objSearchInfo.GroupId = (int)cboGroup.SelectedValue;
objSearchInfo.Name = txtName.Text.Trim();
if(chkFrom.Checked)
objSearchInfo.FromDate = datefrom.Value;
if(chkTo.Checked)
objSearchInfo.ToDate = dateto.Value;
objSearchInfo.SortBy = (rdoasc.Checked) ? Globals.SortBy.Asc : Globals.SortBy.Desc;
objSearchInfo.SortByBirthDate = chkbirthdate.Checked; ;
objSearchInfo.SortByGroup = chkGroup.Checked;
objSearchInfo.SortByName = chkName.Checked;
objSearchInfo.SortByTele = chkTele.Checked;
objSearchInfo.TeleNumber = txtTeleNumber.Text.Trim();
objSearchInfo.TelephoneType = (Globals.TelephoneTypes)this.cboTeleTypes.SelectedValue;
// get result from bus logic layer
PersonInfo[] objresult = Person.Find(objSearchInfo);
How to save and retrieve image from database ?Save to database:
save the image from the picturebox to MemoryStream and then save it on database as Byte[]
// prapare the image
if (null != imgperson.Image) // picturebox control
{
MemoryStream stream = new MemoryStream();
imgperson.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
info.Image = stream.ToArray();
}
Retrieve from database:
// display the image
byte[] PImage = info.Image;
if (null != PImage)
{
MemoryStream stream = new MemoryStream(PImage);
imgperson.Image = Image.FromStream(stream);
}
Restoring Database on SQL Server 2005
Attach the database AhmedEid_PhoneBook.mdf from the directory DataBase on the root directory to the SQL Server Engine.
Debugging Scenario
Let us debug the advanced search button code to retrieve results with criteria from the client
the following scenario will lead you to understand the Provider implementation
make breakpoints as the following
1- AdvancedSearch form class ( presentation layer )
2- Person class of BusinessLogicLayer ( BLL layer )
3- PersonProvider Class of DataAccessLayer ( DAL layer )
4- InittMember<T> class of DataAccessLayer ( DAL layer )
the above code will provide and add the SqlPersonProvider class to the providers list to be available for any usage.
5- SqlGroupProvider class of DataAccesslayer ( DAL layer )
Note: After debugging the code for 1st time , the providers (PersonProvider and groupProvider) will be added to the System.Configuration.Provider.ProviderCollection and for 2nd time the results will be retrieved without instantiating the classes again.
References
- http://msdn.microsoft.com/en-us/library/ms972319.aspx
- http://msdn.microsoft.com/en-us/library/ms972370.aspx
- http://msdn.microsoft.com/en-us/library/ms978496.aspx
- http://en.wikipedia.org/wiki/Design_Patterns
- http://www.c-sharpcorner.com/UploadFile/webmaster3/ProviderPattern12242007184126PM/ProviderPattern.aspx
here, I tried to describe the topic briefly so please don't hesitate to contact me for more information
Thanks
Posted by Bairam.! at 11:56 PM 0 comments
Labels: Architecture / Design, C#, OOP, SQL Server, Visual Studio.NET
Sunday, November 2, 2008
Microsoft SQL Server 2005 Certification from Micrsoft
The last certification from microsoft is :
Posted by Bairam.! at 1:30 AM 1 comments
Labels: Exams and Certifications
Sunday, September 28, 2008
Project Euler Level 1 Congratulations .!
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems. The intended audience include students for whom the basic curriculum is not feeding their hunger to learn, adults whose background was not primarily mathematics but had an interest in things mathematical, and professionals who want to keep their problem solving and mathematics on the edge. The problems range in difficulty and for many the experience is inductive chain learning. That is, by solving one problem it will expose you to a new concept that allows you to undertake a previously inaccessible problem. So the determined participant will slowly but surely work his/her way through every problem.www.projecteuler.net
What is Project Euler?
The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.Who are the problems aimed at?
Can anyone solve the problems?
Posted by Bairam.! at 2:50 AM 0 comments
Labels: Community, Exams and Certifications
Saturday, September 27, 2008
T-Mobile G1™ with Google™ - Black
Today was a huge day for Google and T-Mobile with the announcement of the first phone to come loaded with Android. The official release date of the T-Mobile G1 will be Wednesday October 22nd. Pre-sales started immediately after the announcement for the upgrade price of $179. The G1 has a 3.2-inch 320 x 480 (HVGA) resolution capacitive touchscreen, a flip-out full QWERTY keyboard, dual-band UMTS HSPA, quadband GSM/GPRS/EDGE, WiFi, GPS and Bluetooth. There’s also a 3.2-megapixel fixed-focus camera, microSD slot (with a 1GB card provided and up to 8GB supported) and a trackball for navigation.
Discover when the T-Mobile G1 hits the shelves s you can pick one up. Register now and be the first on your block to find out when it's available.
Posted by Bairam.! at 12:41 AM 0 comments
Labels: Java, Mobile, Technology News
Tuesday, August 26, 2008
Shallow Copy vs Deep Copy in .NET
hi Developers ,
in that post, i am describing the difference between shallow and deep copy by the use of C# language.
shallow and deep copy are used for copying data between objects.
Shallow Copy:
creating a new object, and then copying the nonstatic fields of the current object to the new object.
If a field is a value type --> a bit-by-bit copy of the field is performed
If a field is a reference type --> the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
in C# and VB.NET, shallow copy is done by the object method MemberwiseClone()
Example:
the following are clsShallow class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class)
public class clsShallow
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsShallow CreateShallowCopy(clsShallow inputcls)
{
return (clsShallow)inputcls.MemberwiseClone();
}
}
public class clsRefSalary
{
public clsRefSalary(int _salary)
{
Salary = _salary;
}
public int Salary;
}
now, let us debug and trace the outputs to do the shallow copy by the use of CreateShallowCopy() method
first, use the following code to call the CreateShallowCopy method from other classes
// Creates an instance of clsShallow and assign values to its fields.
clsShallow objshallow = new clsShallow();
objshallow.Age = 25;
objshallow.EmployeeName = "Ahmed Eid";
// add the ref value to the objshallow
clsRefSalary clsref = new clsRefSalary(1000);
objshallow.EmpSalary = clsref;
// Performs a shallow copy of m1 and assign it to m2.
clsShallow m2 = objshallow.CreateShallowCopy(objshallow);
// then modify the clsref salary value to be 2000
clsref.Salary = 2000;
// so the m1 object salary value become 2000
int EmpSalary = objshallow.EmpSalary.Salary;
After assigning the values (value and ref types ones) to the object objShallow and before doing the shallow copy
the values are : (for the current object value)
Age : 25 (value type)
EmpSalry: has salary value of 1000 (ref type)
then do the shallow copy and modify the value of clsref.salary ,reference field type, then check the values of m2 , new created object. (ref and value fields) again
the values are : (for the new created object)
Age : 25 (value type) a new copy of the objShallow object
EmpSalry: has salary value of 2000 (ref type) a refernce to objShallow.EmpSalry object, which is also referenced to the clsref object.
Note: values of m2.EmpSalry and clsref are the same after modifying the clsref values. (reference type concept)
Deep Copy:
creating a new object, and then copying the nonstatic fields of the current object to the new object.
If a field is a value type --> a bit-by-bit copy of the field is performed
If a field is a reference type --> a new copy of the referred object is performed.
Note: the classes to be cloned must be flagged as [Serializable]
Example:
the following are clsDeep class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class)
[Serializable]
// serialize the classes in case of deep copy
public class clsDeep
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsDeep CreateDeepCopy(clsDeep inputcls)
{
MemoryStream m = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(m, inputcls);
m.Position = 0;
return (clsDeep)b.Deserialize(m);
}
}
[Serializable]
public class clsRefSalary
{
public clsRefSalary(int _salary)
{
Salary = _salary;
}
public int Salary;
}
now, let us debug and trace the outputs to do the deep copy by the use of CreateDeepCopy() method
first, use the following code to call the CreateDeepCopy method from other classes
// Creates an instance of clsDeep and assign values to its fields.
clsDeep objdeep = new clsDeep();
objdeep.Age = 25;
objdeep.EmployeeName = "Ahmed Eid";
// add the ref value
clsRefSalary clsref = new clsRefSalary(1000);
objdeep.EmpSalary = clsref;
// Performs a shallow copy of m1 and assign it to m2.
clsDeep m2 = objdeep.CreateDeepCopy(objdeep);
// then modify the clsref salary value to be 2000
clsref.Salary = 2000;
// so the m1 object salary value become 2000
int EmpSalary = objdeep.EmpSalary.Salary;
After assigning the values (value and ref types ones) to the object objDeep and before doing the deep copy
the values are : (for the current object value)
Age : 25 (value type)
EmpSalry: has salary value of 1000 (ref type)
then do the deep copy and modify the value of clsref.salary ,reference field type, then check the values of m2 , new created object. (ref and value fields) again
the values are : (for the new created object)
Age : 25 (value type) a new copy of the objDeep object
EmpSalry: has salary value of 1000, a new copy of the objDeep object
Note: values of m2.EmpSalry and objDeep.EmpSalary are not the same as deep copy creates a new object of the reference type (objDeep.EmpSalary) in m2.EmpSalry. but clsref and objDeep.EmpSalary are the same (Refernce type concept)
With the help of Google I found a very smart method for performing deep copy. Its performance is good than the one i used on that post.
/// <summary>
/// Using generics will solve some performance issues
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
/// <returns></returns>
public static T DeepCopy<T>(T item)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}
i hope that post help you to deeply understand the difference b/w shallw and deep copy in .NET
Ahmed Eid
Posted by Bairam.! at 6:28 AM 0 comments
Labels: C#, OOP, Tricks, Visual Studio.NET
Sunday, August 24, 2008
Code Review Checklist
Posted by Bairam.! at 4:43 AM 0 comments
Labels: Architecture / Design, Coding Standards, Visual Studio.NET
.NET Coding Standards
Hi .NET developers and team leaders,
According to my practical work on Microsoft Visual Studio.NET, it were obligated to use standards for coding, design and implementation. I readed carefully about standards and naming conventions from multiple sources and summarized it then added some modifications to unify our .NET development among the team.
This topic defines some of the standards related to the formatting, naming conventions, and organization for any code written for software development.
All developers implementing HTML, Active Server Pages (ASP) and .NET application should comply with the standards outlined below. Also, each Development manager should strictly enforce these standards during all phases of application development. This document should be used as a guiding principle during all source code reviews and sign-off.
the following are some headlines of our coding standards to be discussed here:
- Documentation
- Naming Conventions
- Hints and Remarks
OK, lets start describing the following items:
- Documentation
You should know that work on a team and may be you leave them for another company, so you should document your work task by task. I followed a lot of problems to understand friends' code on my team after moving to another company. Story
I were working on Human resource management system on my company, and after movement of some colleagues to another company i faced difficulty to understand their codes especially the ones which are not documented. so i asked from my team leader to re-implement some works of it and he approved my point.
- File Header The File header should include:
///////////////////////////////////////
/// creator name: Ahmed Eid
/// creation date: 1 jan 2008
/// description : Handles the submittion of Adduser.aspx
/// edited By : Hany Mohamed
/// updated date: 2 feb 2003
/// reason for update: fixing number over flow bug
///////////////////////////////////////
Note: if developers use visual source safe or TFS , it will be easy to track the changes of file modifications.
- In line Comments developers should document methods and each line code need to documented within classes.
Method documentation:
/// <summary>
/// Here is the description of method functionality
/// </summary>
/// <param name="Param1">describe each param usage</param>
/// <param name="Param2">describe each param usage</param>
/// <param name="Param3">describe each param usage</param>
public void DoSomeThing(int Param1,string Param2,out int Param3)
{
// do somethiong method
}
Note: if you finished method signature, only write /// on the line above your method to prepare the documentation as above.
Inline documentation:
if the code lines need to be described, you must do to be reference for all of reviewing that code ( may be you return back to your code but you could not understand it )
2. Naming Conventions
visual studio.NET
- Files Name Files should be named a descriptive name and they should not be named with numbers for example: submitorder1.asp , submitorder2.asp … Descriptive file name samples:
- adduser.aspx
- viewUserDetails.aspx
- viewAccoutStatus.aspx
- reportUsersPerCountry.aspx
- For shadow pages(pages that execute code on the server and redirects the user) acAdduser.aspx (ac is for action)reGenerateAccessXML.aspx
According to the use of DNN we will add a prefix [ mod_ ] to user controls names if this UC will be defined as DNN module Ex. Mod_ adduser.ascx
- Files Structure A well structure should always be in place; the files should not all be under one folder. Structure can be defined according to factors:
- Based on application business purpose normally for public site
- / (Root)
- Product-X
- Admin
AddUser.aspx - EditUser.aspx
- ....
- Registeration
- Register.aspx
- Confirm.aspx
- EditUser.aspx
- ....
- Product-Y
- ...
- Component-X (may be other .NET application added to solution)
- ...
- Reports
- ...
- ...etc
- Product-X
- Class Name: Class Names should be Nouns and the First letter of the class name should be Caps and the rest of the name should be small.
Samples:
- Connection (good old ADO connection)
- User
- Product This class names shows that a class is an entity that performs an action. Not the action itself.
Hence class names like these
- ManageUsers
- DbFunctions
Naming above gives the idea of something wrong in the design/implementation itself.
Correct naming is:
- Users or UserManagement
- DbAccessLayer
This case pplies on everything (almost) except for the static classes like those who has global functionality. And supports other class
- Methods Names Methods Names should be verbs and it should be written with the Camel Naming convention system which is to write every first letter of the name with CAPS and the rest small without the verb itself example: GetUserInfo(), GetUserPassword()
- Variables
- Control Names The following list of Control Names is to be used when creating names for HTML elements, Control names. When naming an element, the prefix is concatenated with a unique name for the element.
Label --> LblCountryName
TextBox --> txtCountryName
CheckBox --> chkCountry
Optionbox --> optCountry
drobdownlist --> ddlCountry
Combobox --> cmbCountry
ListBox --> lstCountry
Button --> btnCountry
TreeView--> trvCountry
ListView --> lstvCountry
Progressbar --> pbCountry
DataGrid --> dgCountry
Repeater --> rptCountry
DataList --> dlCountry
Image --> imgCountr - Database
- Tables
- Tables’ names will not start with any initials but rather with the name right away.
For example: Customers instead of [Database prefix]_TableName. like : hr_ Employees - Tables’ names should not contain any spaces whatsoever (all spaces should be replaced with underscores).
- Tables’ names should be plural when applicable. For example: Users not User, Customers not Customer. · All tables’ names should be descriptive.
° Variables name should never be x , y, z or i or any other chars that are not descriptive.
° Variables names should consists of the first letter of the variable type and the rest should be the use of the variable
° Variables name should be written using the Camel Naming convention system. Example: iUserId, sUserName
° Boolean Variables should be Positive sense Names example: isEmpty, isActive
integer --> iUserId
double --> dBasicSalary
string --> sName
float --> fPercent
..... and so onNote: you can customize your naming conventions as you like you must keep that standard among team. you may write string as strName
- Table Fields
- pfk = primary foreign key & lfk = logical foreign key
- All fields’ names should be descriptive
- For the identity it will be AutoId For the foreign key it will be prefix_fieldName
- The foreign key from another table of the current database will be pfk_CustomerId
- The foreign key from another database table or external file structure like XML,..etc will be lfk_userI
- Fields names should not contain any spaces whatsoever (all spaces should be replaced with underscores)
- Views
- All views’ names should be descriptive
- All views names should start with database prefix For example: hrvw_Employee
- Stored Procedures
- All stored procedures’ names should be descriptive
- All stored procedure names should start with a database prefix instead of SP since system stored procedures start with sp. For example: hr_AddEmployee
and so on .....
3. Hints and Remarks
- Avoid Late Binding
- Use StringBuilder class for string manipulation (don’t use string class)
- Web Development should also Cache there Page
- Developer has to use the .NET field validation for each of the following validation
- Mandatory
- Email format
- Phone Format
- Range like the age range
- Password and password confirmation Comparison
- Errors messages:
- Should be spell checked
- Should be in a proper and consistent format
- Correct messages are displayed for each condition
- Messages useful & meaningful for the user (e.g. “Driver error 80004005” will not be understood by a normal user)
- Different errors are handled by different messages (invalid data types & entry length can not have the same message)
- All Javascripts and VB scripts should be in one block in the beginning or the end of the file
- All HTML tags should be small letters
- Any developer using .NET should use regions when ever possible to have a better and easier look at his code
these are some coding standards we use on .NET environment development. so you could follow them or customize it to match your case.
if you have any inquiry about that topic, please don't hesitate to contact me at aes_fci@hotmail.com
Thanks
Posted by Bairam.! at 2:00 AM 1 comments
Labels: Architecture / Design, Coding Standards, SQL Server, Visual Studio.NET
| ||||||||||||||||||||||