Useful links on LINQ to XML, XML, ASP.NET MVC

Reading XML + LINQ
Reading XML and LINQ 1
Reading XML and LINQ 2

Linq to XML
LINQ to XML 1
LINQ to XML 2
LINQ to XML 3
LINQ to XML 4
LINQ to XML 5
LINQ to XML 6
LINQ to XML 7
LINQ to XML 8
LINQ to XML 9
LINQ to XML 10
LINQ to XML 11

Linq to XML + Excel
LINQ to XML and Excel 1

ASP.NET MVC + XML
ASP.NET MVC and XML 1
ASP.NET MVC and XML 2

CRUD + XML + ASP.NET MVC3
CRUD, XML and ASP.NET MVC 3

Aside | Posted on by | Leave a comment

Samsung Service Center in the Philippines

http://www.samsung.com/ph/support/location/supportServiceLocation.do

1    PHONEVILLE MOBILE INC.     Unit 003 Ground Floor Cyberzone Area SM City Manila
2    WSI PHONECARE, INC.    Samsung Customer Service Unit CZ-018, Lower G/F, SM City Manila

1    SERVCARE SOLUTIONS PHILIPPINES INC.    Jaka Center, #2111 Don Chino Roces (Pasong Tamo), Makati City
2    WELLCOM TELECOM SUPERMARKET INC.    Laptop Zone, Parksquare, Ayala (front of Glorietta 1)
3    WSI PHONECARE, INC.    7F SEDCCO Bldg., Rada corner Legaspi Sts., Legaspi Village, Makati City

Posted in Service Center | Leave a comment

HP Service Center in the Philippines

http://www8.hp.com/ph/en/contact-hp/office-locations.html#2

Main office:
37th Floor Robinsons Summit Center
6783 Ayala Avenue
Makati City, Philippines

Trunk Line: (632) 888-5900
Fax Line: 830-7300

8:30am to 5:30pm / Monday to Friday
Two and Three World Square
22 Upper McKinley Road, McKinley Hill Town Center, Fort Bonifacio,
Taguig City 1634
Reception: (632) 902-6000

Intellectual Property Center
28 Upper Mckinley Road, Mckinley Hill Town Center, Fort Bonifacio
Taguig City 1634
Reception: (632) 718-7073

HP Service Centers:
GF Accelerando Building,
395 Sen. Gil Puyat Avenue, Makati City

Tel. No. (632) 888-6100
Unit C-D-E Ground Floor
Capitol Centrum Bldg.
Clavano cor. Escario St. Cebu City

Tel. No. (032) 254-4548 or (032) 412-5300

Posted in Service Center | Leave a comment

Useful Links for .NET Programmer

ReportViewer 2012 AND IIS 7
ReportViewer 2012 AND IIS 7 Reference #1
ReportViewer 2012 AND IIS 7 Reference #2

Logging Error in ASP.NET
Logging Error in ASP.NET Reference 1
Logging Error in ASP.NET Reference 2
Logging Error in ASP.NET Reference 3
Logging Error in ASP.NET Reference 4
Logging Error in ASP.NET Reference 5

Hover Menu Extender sample
Hover Menu Extender sample

Remove annoying arrow at menu
Remove annoying arrow at menu

SKyDrive Sample Codes
SKyDrive Sample Codes Reference 1
SKyDrive Sample Codes Reference 2

HoverMenuExtender
HoverMenuExtender Reference 1
HoverMenuExtender Reference 2
HoverMenuExtender Reference 3
HoverMenuExtender Reference 4

Showing Images on MouseOver
Showing Images on MouseOver

Cache, Session and Viewstate
Cache, Session and Viewstate

Loading Related Entities
Loading Related Entities

ASP.NET Session Timeout
ASP.NET Session Timeout

ASP.NET Viewstate
ASP.NET Viewstate Reference 1
ASP.NET Viewstate Reference 2

Cell padding
Cell padding

vertical align css 3
vertical align css 3

Ajax-Based JavaScript File Uploader with Progress Bar
Ajax-Based JavaScript File Uploader with Progress Bar

jQuery File Upload Plugin
jQuery File Upload Plugin

ASP.NET File Upload with Progress Bar
ASP.NET File Upload with Progress Bar

FileUpload
FileUpload Reference 1
FileUpload Reference 2
FileUpload Reference 3

flex container
flex container

Chosen Plugin Dropdownlist?
Chosen Plugin Dropdownlist?

Textbox Autocomplete
Textbox Autocomplete

ASp.NEt Autocomplete Dropdownlist
ASp.NEt Autocomplete Dropdownlist

Validator for Checkboxlist references:
Validator for Checkboxlist References 1
Validator for Checkboxlist References 2
Validator for Checkboxlist References 3
Validator for Checkboxlist References 4

Guid password generator
Guid Password Generator

Posted in .NET Framework 4, Ajax Control, ASP.NET, CSS, JQuery | Leave a comment

Migrating to HTML 5 using ASP.NET 4.5

Let us say, you have previous aspx page that you copy and paste. You use HTML 5 in visual studio 2012. When you try to compile, it will give you a compile error.
Please change align=”left” to style=”text-align:left”. Please change align=”right” to style=”text-align:right”. Please change align=”center” to style=”text-align:center”.

Posted in ASP.NET 4.5, HTML 5 | Leave a comment

Migrating EF4 to EF4.5

If you do have a previous class that uses entity framework in visual studio 2010. Then you need to create the same class using visual studio 2012. When you try to copy and paste into the new class. Then compile it, it will give you an error. In visual studio 2010 Addto<tablename> method and DeleteObject method no longer exist. Please use <tablename>.Add method and <tablename>.Remove method respectively.

Posted in C# 4.5, Entity Framework 4.5, Linq to Entity | Leave a comment

How to validate an Ajax control combo box has item selected or not?

First, you need to insert beside the combo box a custom validator like this,

CustomValidatorSampleCode
If your combo box default selected value is an empty string then you need to add a function inside a script tag like this,

function CustomValidator(s, e) {
if ($find(s.controltovalidate)._textBoxControl.value == "") {
e.IsValid = false;
}
}

If your combo box default value of “Please select” then you need to add a function inside a script tag like this,

function CustomValidator(s, e) {
if ($find(s.controltovalidate)._textBoxControl.value == "Please select") {
e.IsValid = false;
}
}

References used:
Reference used

Posted in Ajax Control, ASP.NET 4, ASP.NET 4 And Javascript | Leave a comment

How fix the column width in a gridview at insert tooltip in each cell in Asp.net 4?

If you need to set the width of each column in a gridview control, If the column is just to display and no editing needed. You can like this,

FixColumnWidth1

But if there is a editing to be done, you need to do like this,

FixColumnWidth2

If you need insert a tooltip for each cell inside a gridview, you need to set each column tooltip. You can do like this,

protected void gv_DataBound(object sender, EventArgs e) { Label lbl = new Label(); foreach (GridViewRow rv in gv.Rows) { lbl = (Label)rv.FindControl("lblGridColumnName "); rv.Cells[1].ToolTip = lbl == null ? string.Empty : lbl.Text; } }

Posted in ASP.NET 4, C# 4.0, C# 4.0 AND ASP.NET 4.0, CSS | 1 Comment

How to manipulate back button in ASP.NET 4?

After searching a lot of references. I have came to a conclusion that you can only prevent user from accessing the previous page is thru javascript window history. You can not manipulate the forward button but only the back button. There are many ways to do it, if you really want to manipulate both button is to clear cache like this,
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
Response.Expires = 0;
Response.CacheControl = “no-cache”;

To manipulate the previous page (back button) is thru this way,

<script type=”text/javascript” language=”javascript”>

function DeleteHistory() {
window.history.go(‘Default.aspx’);
}
setTimeout(“DeleteHistory()”, 1000);
window.onunload = function () { DeleteHistory(); };
</script>

Here are references that I have used:
Reference 1
Reference 2
Reference 3
Reference 4
Reference 5
Reference 6
Reference 7
Reference 8
Reference 9
Reference 10
Reference 11

Javascript back button asp.net
Reference 12
Reference 13
Reference 14
Reference 15
Reference 16
Reference 17
Reference 18
Reference 19

Posted in ASP.NET 4, ASP.NET 4 And Javascript, JavaScript | Leave a comment

Microsoft Product End of Suport Date

The following microsoft product end of support date and end of sales date.
Windows Lifecycle Fact Sheet Window OS Products

Visual Studio Lifecycle Fact Sheet
Visual Studio Product

SQL Server Lifecycle Fact Sheet
SQL Server Products

Posted in End of Support Date, SQL Server, Visual Studio, Windows OS | Leave a comment

Optimize performance of your Entity Framework 4 on Client Side

If you want to improve the perforamance of your entity framework in client side, you can use Cache from
System.Web.Caching.Cache object. If you like to reset values,
Cache.Remove(“Name of your Cache”);
If you wish to store the value to a cache,
if (Cache.Get(“Name of your Cache”) == null)
    Cache.Insert(“Name of your Cache”, object);
Where your object can be dataset or datatable or list.

You can determine which part of your code that needs to refactor your existing code using Entity Framework Profiler.
Entity Framework Profiler

Reference 1
Reference 2
Reference 3

Reference 4
Reference 5
Reference 6
Reference 7
Reference 8

Reference 9
Reference 10
Reference 11

Reference 12
Reference 13
Reference 14

Aside | Posted on by | Leave a comment

Troubleshooting your rdlc inside Visual Studio 2010.

In order to troubleshoot your rdlc inside Visual Studio 2010.

Problem: how to make table invisible when there is no row.

Solution:  Set the expression for the row,

=IIF(Fields!BILLER.Value is nothing, true, false)

Step 1: Right click the tablix, choose and click row visibility.

Step 2: Choose and click the button beside “Show or hide based on an expression”.

Step 3: Enter the expression, =IIF(Fields!BILLER.Value is nothing, true, false).

Problem 2: How to display the image inside the report viewer.

Solution: You need to set the UI culture and culture for an individual page, set the Culture and UICulture attributes of the @ Page directive, as shown in the following example:

<%@ Page UICulture=”es” Culture=”es-MX” %>

To insert image on the report itself.

Step 1: Right click and choose insert then choose and click on image.

Step 2: Click on import button.

Step 3: Choose and click on the image.

Problem 3: How to create a variable that will make computations, like quantity multiply price equals sales.

Solution:

Step 1: Find and Click on Report Properties.

Step 2: Find and click onVariables.

Step 3: Click Add Button.

Step 4: Enter your chosen name. Then click on “fx” button.

Step 5: Enter your expression after the equal sign.

References used:

Reference 1

Reference 2

References 3

Reference 4

Reference 5

Reference 6

Reference 7

Reference 8

Reference 9

Note: I will include the images in this post next time.

Posted in Reporting Service Client (RDLC), Reporting Services 2008, Visual Studio 2010 | Leave a comment

Useful links for SQL Server 2008 and Visual Studio 2010 Service Pack

Useful links for SQL Server 2008 and Visual Studio 2010 Service Pack

SQL Server 2008 SP1

SQL Server 2008 SP2

SQL Server 2008 SP3

SQL Server 2008 R2 SP1

SQL Server 2008 R2 SP2

Microsoft SQL Server 2008 SP2 Reporting Services Report Builder

Microsoft Visual Studio 2010 Service Pack 1

Security Update for Microsoft Visual Studio 2010 Service Pack 1 (KB2645410)

Update for Microsoft Visual Studio 2010 Service Pack 1 Report Viewer (KB2549864)

Visual Studio 2010 Performance Tools with Service Pack 1

Visual Studio 2010 Remote Debugger with Service Pack 1

Update for Microsoft Visual Studio 2010 Service Pack 1 Web Platform Tools

Update for Microsoft Visual Studio 2010 Service Pack 1 (KB2635973)

Microsoft Visual Studio 2010 Service Pack 1 MFC Security Update

Update for Microsoft Visual Studio 2010 Service Pack 1 (KB2529927)

Update for Microsoft Visual Studio 2010 Service Pack 1 TFS Build Explorer (KB2522890

Microsoft Report Viewer Redistributable 2005 Service Pack 1

Microsoft Report Viewer 2008 SP1 Redistributable

Microsoft SQL Server 2008 R2

Microsoft Report Viewer 2010 Redistributable Package

.NET Framework 4

Microsoft .NET Framework 4 KB2468871

Update 4.0.2 for Microsoft .NET Framework 4 – Design-time Update for Visual Studio 2010 SP1 (KB2544525)

Multi-Targeting Pack for Microsoft .NET Framework 4.0.2 (KB2544526)

Microsoft .NET Framework 4 Platform Update 1 – Design-time Update for Visual Studio 2010 SP1 (KB2495593)

Update 4.0.2 for Microsoft .NET Framework 4 – Runtime Update (KB2544514)

Microsoft .NET Framework 4 Platform Update 1 – Runtime Update (KB2478063)

Posted in Reporting Services 2008, SQL Server 2008, Visual Studio 2010 | Leave a comment

How to create and use web site template in visual studio 2010?

this blog shows you on how to create and use web site template in visual studio 2010.  Before creating a template, you need to create a web site or project that you like to create a template.

Step 1: Click on File then find and click on Export Template.

Step 2: On Choose Template Type, choose project or item template, then choose which project you like to create a template, and then choose either C #or VB.NET.

Step 3: You will see your entire project in this solution. You need to pick one. Then click on next.

Step 4: You can provide template name, template description, icon image, preview image. Then click on finish button.

Step 5: Go to you’re my computer, Here is a sample path, C:\Users\<user name>\Documents\Visual Studio 2010\My Exported Templates. You can see your template in zip format.

Step 6: Copy and paste the zip file from C:\Users\<user name>\Documents\Visual Studio 2010\My Exported Templates\ to C:\Users\<user name>\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#\.

Step 7: Click on File, then click on new web site, find and choose your newly created template. Type your project name and then click OK.

In case that the export template is missing, try to reset settings. Find and click on Tools, then find and click Import and Export Settings.

References:

http://msdn.microsoft.com/en-us/library/ms185291.aspx

http://msdn.microsoft.com/en-us/library/ms185311.aspx

http://msdn.microsoft.com/en-us/library/ms247065.aspx

http://msdn.microsoft.com/en-us/library/y3kkate1.aspx

http://msdn.microsoft.com/en-us/library/s365byhx.aspx

http://msdn.microsoft.com/en-us/library/xkh1wxd8.aspx

http://www.bluelemoncode.com/post/2012/01/20/Creating-custom-project-template-for-Visual-Studio-with-pre-installed-NuGet-packages.aspx

http://www.carlosag.net/articles/create-vs-template

http://www.codeproject.com/Articles/88957/Write-Templates-for-Visual-Studio-2010

http://www.asp.net/whitepapers/aspnet4

VSIX

http://msdn.microsoft.com/en-us/library/dd885241.aspx

http://msdn.microsoft.com/en-us/library/dd393742.aspx

http://www.microsoft.com/download/en/details.aspx?id=2680

Note: I have not yet included any images in this post.

Posted in .NET Framework 4, C# 4.0 AND ASP.NET 4.0, Project Template, Web site Template | Leave a comment

How to create reports (rdlc) and load inside report viewer?

This blog will show you how to create report (rdlc not rdl) and display inside report viewer not thru browser. This post also shows you on how to use entity framework as a data source.

Step 1 – Find and Choose Report Wizard. You need to type your chosen report name.

Step 2 – Type in your chosen dataset name at dataset properties. Then click on Add button.

Step 3 – Either choose existing data source or create new data source. If you choose existing data source and select item from the drop down list. If you choose to create new connection, you need to click the button beside the drop down list.

Step 4 – Use the drop down list to select available dataset.

Step 5 – At Arrange fields, drop and drop items from Available fields to Values section.

Step 6 – Once you finish drag and drop, click next.

Step 7 – Click next.

Step 8 – Choose a style from the list. Click next.

Step 9 – Report Data will be display all fields selected.

Step 10 – The report will be displayed.

Step 11 – Right click on report viewer properties and set local report’s report path and data sources.

This is sample code, wherein you set data source and parameters of your report.

string Param1 = this.ddl_Param1.SelectedValue== “0” ? string.Empty : this.ddl_Param1.SelectedValue;

string Param2 = this.ddl_Param2.SelectedValue == “0” ? string.Empty : this.ddl_Param2.SelectedValue;

string Param3 = this.ddl_Param3.SelectedValue == “0” ? string.Empty : this.ddl_Param3.SelectedValue;

string Param4 = this.ddl_PARAM4.SelectedValue == “0” ? string.Empty : this.ddl_PARAM4.SelectedValue;

#region “ReportDataSource”

if (_myClassLibrary == null)

_myClassLibrary = new MyClassLibrary();

var list = new List<Entity>();

list = _myClassLibrary.myMethod(Param1, Param2, Param3, Param4);

this.Reportviewer.LocalReport.DataSources.Clear();

this.Reportviewer.LocalReport.DataSources.Add(new ReportDataSource(“DataSet1″, list));

#endregion

var Param1Param = new ReportParameter(“Param1″, Param1);

var Param2Param = new ReportParameter(“Param2Id”, Param2);

var Param3Param = new ReportParameter(“Param3Code”, Param3);

var Param4Param = new ReportParameter(“Param4Id”, Param4);

this.Reportviewer.LocalReport.SetParameters(new[] {Param2Param});

this.Reportviewer.LocalReport.SetParameters(new[] {Param3Param});

this.Reportviewer.LocalReport.SetParameters(new[] {Param1Param});

this.Reportviewer.LocalReport.SetParameters(new[] {Param4Param});

References:

http://stackoverflow.com/questions/4949205/how-do-i-use-linq-as-datasource-for-a-microsoft-report

http://www.datadynamics.com/forums/128880/PrintPost.aspx

http://heathesh.com/category/LINQ.aspx

http://www.neodynamic.com/ND/FaqsTipsTricks.aspx?tabid=66&prodid=1&sid=66

http://www.neodynamic.com/demo-faq/barcode-net-sdk/how-to-create-local-reports-rdlc-featuring-barcode-images-in-net-windows-forms.aspx

http://www.google.com.ph/url?sa=t&rct=j&q=how+to+create+rdlc+in+.net+4%3F&source=web&cd=4&ved=0CDQQFjAD&url=http%3A%2F%2Fweblogs.asp.net%2Frajbk%2Farchive%2F2010%2F05%2F09%2Fcreating-an-asp-net-report-using-visual-studio-2010-part-1.aspx&ei=-0UNT6iBM8THmQW42cyhBg&usg=AFQjCNGriPTPgbxMTc4VHV4WWBDn_MeIUg&cad=rja

http://www.codeproject.com/KB/reporting-services/DynamicReports.aspx

http://www.barcoderesource.com/RDLCReportBarcode.shtml

http://www.codeproject.com/KB/reporting-services/RDLC_and_DataSet.aspx

http://www.eggheadcafe.com/community/asp-net/17/10378000/how-to-make-rdlc-report.aspx

http://weblogs.asp.net/rajbk/archive/2010/05/09/creating-an-asp-net-report-using-visual-studio-2010-part-1.aspx

Note: I have not put any images yet and will later edit this post if I do have time to edit this post again.

Posted in .NET Framework 4, C# 4.0 AND ASP.NET 4.0, Linq to Entity, RDLC, Report Viewer, Reporting Services 2008 | Leave a comment

Lenovo Useful URL Links

Useful links

http://consumersupport.lenovo.com/ph/en/Guides/Guide_list.aspx?CategoryID=633979 http://consumersupport.lenovo.com/ph/en/Member/Warranty_registration.aspx http://consumersupport.lenovo.com/ph/en/Warranty/Warranty.html http://consumersupport.lenovo.com/ph/en/Warranty/IWS_Status_Lookup.aspx http://consumersupport.lenovo.com/ph/en/Introduction/Introduction.html http://consumersupport.lenovo.com/ph/en/serviceproducts/Service.html http://consumersupport.lenovo.com/ph/en/supportphonelist/supportphone.aspx http://consumersupport.lenovo.com/ph/en/Maintenancestation/APR_Maintenancestation.aspx http://consumersupport.lenovo.com/ph/en/Guides/Guide.html http://consumersupport.lenovo.com/ph/en/TroubleShooting/TroubleShooting.html

Posted in Laptop, Lenovo, Lenovo Service Center, Lenovo Z460 | Leave a comment

Using ReportViewer in ASP.NET 4.0 and Entity Framework

To bind a data source to a reportviewer:

Add this line after <%@ Page … ,

<%@ Register Assembly=”Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”
Namespace=”Microsoft.Reporting.WebForms” TagPrefix=”rsweb” %>

<rsweb:ReportViewer ID=”ReportName” BorderStyle=”Solid” BorderColor=”Gray”
BorderWidth=”1px” runat=”server” Font-Names=”Verdana” Font-Size=”8pt” InteractiveDeviceInfos=”(Collection)”
WaitMessageFont-Names=”Verdana” WaitMessageFont-Size=”14pt” Width=”100%” Height=”470px”>
<LocalReport ReportPath=”ReportPath.rdlc”>
</LocalReport>
</rsweb:ReportViewer>

At the code behind,

DataSource _datasource = new DataSource();
ReportDataSource itm = new ReportDataSource(“ReportDataSourceName”, _datasource.GetDataSourceList(this.HiddenField.Value));

To setup parameters of reportviewer:

var messageParam = new ReportParameter(“Message”, Value);

this.ReportName.LocalReport.SetParameters(new[] { messageParam });

Conclusion: This blog need to be edited further.
References:

http://heathesh.com/category/LINQ.aspx

Posted in .NET Framework 4, C# 4.0 AND ASP.NET 4.0, Linq to Entity, Visual Studio 2010 | Leave a comment

CodeSmith: Software Development Tool

CodeSmith is a software development tool to help you get your job done faster. Technically speaking it is a template driven source code generator that automates the creation of common application source code for any language (C#, Java, VB, PHP, ASP.NET, SQL, etc.) or any text based output.

CodeSmith enables software developers to efficiently:

• Reduce repetitive coding
• Generate your code in less time with fewer bugs
• Produce consistent code that adheres to your standards
• Create your own custom templates for any language

CodeSmith Generator Features

• CodeSmith Studio – CodeSmith Studio makes building your own custom templates very easy. With Intellisense you can create or modify your templates with ease.

• Visual Studio Integration – With integration into the MSBuild pipeline and Visual Studio 2005/2008/2010, you can actively generate without ever leaving Visual Studio. Visual Studio integration also features the ability to create your own active snippets for common tasks like creating properties from metadata.

• Template Debugging – CodeSmith makes it easy to debug your templates by providing the CodeSmith template developer with the line number in the template where the problem occurred.

• Rich XML and MetaData Support – The XmlProperty directive allows you to easily use XML to drive your templates. If an XSD schema is provided, a strongly typed XML object model will automatically be generated and makes working with XML simple.

• Merge Capabilities – The merging capabilities in CodeSmith allow you to merge generated and hand written code within a single file.

• Master templates – Provide an efficient way to execute many templates known as sub-templates at one time. Master Templates are very useful when creating dynamic, structured and well controlled output.

• Active Community – Join in and collaborate with other CodeSmith users about questions, issues or ideas that you may have.

• Console Client – The console client allows you to easily automate your code generation process and can execute templates one at a time or in batches.

• Auto SQL Script Execution – Templates that generate SQL scripts can be auto-executed after generation allowing for easy deployment of generated SQL code.

• Fast Compiler & Template Caching – CodeSmith can compile and execute your custom templates very fast and efficiently.

Supported Template Frameworks

• LINQ to SQL (PLINQO) – Replace and enhance Microsoft’s LINQ to SQL with PLINQO. These open source CodeSmith templates open the LINQ to SQL black box, giving you the ability to control your source code while adding many new features and enhancements. It’s still LINQ to SQL, but better!

• CSLA – Generate CSLA in minutes with our CodeSmith CSLA templates. Rockford Lhotka’s CSLA .NET framework is an application development framework that reduces the cost of building and maintaining applications.

• NHibernate – NHibernate is a port of Hibernate Core for Java to the .NET Framework. It handles persisting plain .NET objects to and from an underlying relational database. Given an XML description of your entities and relationships, NHibernate automatically generates SQL for loading and storing the objects. Optionally, you can describe your mapping metadata with attributes in your source code.

• .netTiers – .netTiers is a set of open source code generation templates that simplify the tasks of creating customized Application Tiers for your Microsoft.Net applications in just a few minutes. .netTiers generated architecture is custom to your domain, uses familiar patterns, and follows the guidance of Microsoft’s recommended patterns and practices. In fact, the .netTiers base architecture is built upon the Microsoft Enterprise Library Application Blocks.

http://www.codesmithtools.com

Posted in Code Generator, Software Development Tool | Leave a comment

Useful System SPs of SQL Server 2005

sp_add_data_file_recover_suspect_db (Transact-SQL)
Adds a data file to a filegroup when recovery cannot complete on a database due to insufficient space on the file group (error 1105). After the file is added, this stored procedure turns off the suspect setting and completes the recovery of the database. The parameters are the same as those for ALTER DATABASE database_name ADD FILE.
Click this link

sp_addextendedproc (Transact-SQL
Registers the name of a new extended stored procedure to Microsoft SQL Server.
Click this link

sp_addextendedproperty (Transact-SQL)
Adds a new extended property to a database object.
Click this link

sp_add_log_file_recover_suspect_db (Transact-SQL)
Adds a log file to a file group when recovery cannot complete on a database due to insufficient log space (error 9002). After the file is added, sp_add_log_file_recover_suspect_db turns off the suspect setting and completes the recovery of the database. The parameters are the same as those for ALTER DATABASE database_name ADD LOG FILE.
Click this link

sp_addmessage (Transact-SQL)
Stores a new user-defined error message in an instance of the SQL Server Database Engine. Messages stored by using sp_addmessage can be viewed by using the sys.messages catalog view.
Click this link

sp_addtype (Transact-SQL)
Creates an alias data type.
Click this link

sp_addumpdevice (Transact-SQL)
Adds a backup device to an instance of the Microsoft SQL Server 2005 Database Engine.
Click this link

sp_altermessage (Transact-SQL)
Alters the state of user-defined messages in an instance of the SQL Server Database Engine. User-defined messages can be viewed using the sys.messages catalog view.
Click this link

sp_attach_db (Transact-SQL)
Attaches a database to a server.
Click this link

sp_attach_single_file_db (Transact-SQL)
Attaches a database that has only one data file to the current server. sp_attach_single_file_db cannot be used with multiple data files.
Click this link

sp_autostats (Transact-SQL)
Displays or changes the automatic UPDATE STATISTICS setting for a specific index and statistics, or for all indexes and statistics for a specified table or indexed view in the current database.
Click this link

sp_batch_params (Transact-SQL)
Returns a rowset that contains information about the parameters included in a Transact-SQL batch. sp_batch_params only parses the batch specified and returns information about embedded parameter values. It does not execute the batch or modify the execution environment.
Click this link

sp_bindefault (Transact-SQL)
Binds a default to a column or to an alias data type.
Click this link

sp_bindrule (Transact-SQL)
Binds a rule to a column or to an alias data type.
Click this link

sp_bindsession (Transact-SQL)
Binds or unbinds a session to other sessions in the same instance of the SQL Server Database Engine. Binding sessions allows two or more sessions to participate in the same transaction and share locks until a ROLLBACK TRANSACTION or COMMIT TRANSACTION is issued.
Click this link

sp_certify_removable (Transact-SQL)
Verifies that a database is correctly configured for distribution on removable media and reports any problems to the user.
Click this link

sp_configure (Transact-SQL)
Displays or changes global configuration settings for the current server.
Click this link

sp_control_plan_guide (Transact-SQL)
Drops, enables, or disables a plan guide.
Click this link

sp_create_plan_guide (Transact-SQL)
Creates a plan guide for associating query hints with queries in a database.
Click this link

sp_create_removable (Transact-SQL)
Creates a removable media database. Creates three or more files (one for the system catalog tables, one for the transaction log, and one or more for the data tables) and places the database on those files.
Click this link

sp_createstats (Transact-SQL)
Creates single-column statistics for all eligible columns for all user tables and internal tables in the current database. The new statistic has the same name as the column where it is created.
Click this link

sp_datatype_info (Transact-SQL)
Returns information about the data types supported by the current environment.
Click this link

sp_db_vardecimal_storage_format (Transact-SQL)
Returns the current vardecimal storage format state of a database, or enables or disables a database for vardecimal storage format. Requires SQL Server 2005 Service Pack 2 or later versions. Vardecimal storage format is available only in SQL Server 2005 Enterprise, Developer, and Evaluation editions.
Click this link

sp_dbcmptlevel (Transact-SQL)
Sets certain database behaviors to be compatible with the specified version of SQL Server.
Click this link

sp_dbmmonitoraddmonitoring (Transact-SQL)
Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance.
click this link

sp_dbmmonitorchangealert (Transact-SQL)
Adds or changes warning threshold for a specified mirroring performance metric.
Click this link

sp_dbmmonitorchangemonitoring (Transact-SQL)
Changes the value of a database mirroring monitoring parameter.
Click this link

sp_dbmmonitordropalert (Transact-SQL)
Drops the warning for a specified performance metric, by setting the threshold to NULL.
Click this link

sp_dbmmonitordropmonitoring (Transact-SQL)
Stops and deletes the mirroring monitor job for all the databases on the server instance.
Click this link

sp_dbmmonitorhelpalert (Transact-SQL)
Returns information about warning thresholds on one or all of several key database mirroring monitor performance metrics.
Click this link

sp_dbmmonitorhelpmonitoring (Transact-SQL)
Returns the current update period.
Click this link

sp_dbmmonitorresults (Transact-SQL)
Returns status rows for a monitored database from the status table in which database mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.
Click this link

sp_dbmmonitorupdate (Transact-SQL)
Updates the database mirroring monitor status table by inserting a new table row for each mirrored database, and truncates rows older than the current retention period. The default retention period is 7 days (168 hours). When updating the table, sp_dbmmonitorupdate evaluates the performance metrics.
Click this link

sp_dboption (Transact-SQL)
Displays or changes database options. Do not use sp_dboption to modify options on either the master database or the tempdb database.
Click this link

sp_dbremove (Transact-SQL)
Removes a database and all files associated with that database.
Click this link

sp_delete_backuphistory (Transact-SQL)
Reduces the size of the backup and restore history tables by deleting the entries for backup sets older than the specified date. Additional rows are added to the backup and restore history tables after each backup or restore operation is performed; therefore, we recommend that you periodically execute sp_delete_backuphistory.
Click this link

sp_delete_database_backuphistory (Transact-SQL)
Deletes information about the specified database from the backup and restore history tables.
Click this link

sp_depends (Transact-SQL)
Displays information about database object dependencies, such as: the views and procedures that depend on a table or view, and the tables and views that are depended on by the view or procedure. References to objects outside the current database are not reported.
Click this link

sp_detach_db (Transact-SQL)
Detaches a database that is currently not in use from a server instance and, optionally, runs UPDATE STATISTICS on all tables before detaching.
Click this link

sp_dropdevice (Transact-SQL)
Drops a database device or backup device from an instance of the SQL Server 2005 Database Engine, deleting the entry from master.dbo.sysdevices.
Click this link

sp_dropextendedproc (Transact-SQL)
Drops an extended stored procedure.
Click this link

sp_dropextendedproperty (Transact-SQL)
Drops an existing extended property.
Click this link

sp_dropmessage (Transact-SQL)
Drops a specified user-defined error message from an instance of the SQL Server Database Engine. User-defined messages can be viewed using the sys.messages catalog view.
Click this link

sp_droptype (Transact-SQL)
Deletes an alias data type from systypes.
Click this link

sp_estimated_rowsize_reduction_for_vardecimal (Transact-SQL)
Estimates the reduction in the average size of rows if enable vardecimal storage format is enabled on a table. Use this number to estimate the overall reduction in the size of the table. Because the statistical sampling is used to compute the average reduction in the rowsize, regard it as an estimate only. In rare cases, rowsize may increase after you enable the vardecimal storage format. Vardecimal storage format is available only in SQL Server 2005 Enterprise, Developer, and Evaluation editions.
Click this link

sp_executesql (Transact-SQL)
Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters.
Click this link

sp_get_query_template
Returns the parameterized form of a query. The results returned mimic the parameterized form of a query that results from using forced parameterization. sp_get_query_template is used primarily when you create TEMPLATE plan guides.
Click this link

sp_getapplock (Transact-SQL)
Places a lock on an application resource.
Click this link

sp_getbindtoken (Transact-SQL)
Returns a unique identifier for the transaction. This unique identifier is a string used to bind sessions using sp_bindsession.
Click this link

sp_help (Transact-SQL)
Reports information about a database object (any object listed in the sys.sysobjects compatibility view), a user-defined data type, or a data type supplied by SQL Server 2005.
Click this link

sp_helpconstraint (Transact-SQL)
Returns a list of all constraint types, their user-defined or system-supplied name, the columns on which they have been defined, and the expression that defines the constraint (for DEFAULT and CHECK constraints only).
Click this link

sp_helpdb (Transact-SQL)
Reports information about a specified database or all databases.
Click this link

sp_helpdevice (Transact-SQL)
Reports information about Microsoft® SQL Server™ backup devices.
Click this link

sp_helpextendedproc (Transact-SQL)
Reports the currently defined extended stored procedures and the name of the dynamic-link library (DLL) to which the procedure (function) belongs.
Click this link

sp_helpfile (Transact-SQL)
Returns the physical names and attributes of files associated with the current database. Use this stored procedure to determine the names of files to attach to or detach from the server.
Click this link

sp_helpfilegroup (Transact-SQL)
Returns the names and attributes of filegroups associated with the current database.
Click this link

sp_helpgroup (Transact-SQL)
Reports information about a role, or all roles, in the current database.
Click this link

sp_helpindex (Transact-SQL)
Reports information about the indexes on a table or view.
Click this link

sp_helplanguage (Transact-SQL)
Reports information about a particular alternative language or about all languages.
Click this link

sp_helpserver (Transact-SQL)
Reports information about a particular remote or replication server, or about all servers of both types. Provides the server name, the network name of the server, the replication status of the server, the identification number of the server, and the collation name. Also provides time-out values for connecting to, or queries against, linked servers.
Click this link

sp_helpsort (Transact-SQL)
Displays the sort order and character set for the instance of SQL Server 2005.
Click this link

sp_helpstats (Transact-SQL)
Returns statistics information about columns and indexes on the specified table.
Click this link

sp_helptext (Transact-SQL)
Displays the definition of a user-defined rule, default, unencrypted Transact-SQL stored procedure, user-defined Transact-SQL function, trigger, computed column, CHECK constraint, view, or system object such as a system stored procedure.
Click this link

sp_helptrigger (Transact-SQL)
Returns the type or types of DML triggers defined on the specified table for the current database. sp_helptrigger cannot be used with DDL triggers. Query the sys.triggers (Transact-SQL) catalog view instead.
Click this link

sp_indexoption (Transact-SQL)
Sets locking option values for user-defined clustered and nonclustered indexes or tables with no clustered index.
The SQL Server 2005 Database Engine automatically makes choices of page-, row-, or table-level locking. You do not have to set these options manually. sp_indexoption is provided for expert users who know with certainty that a particular type of lock is always appropriate.
Click this link

sp_invalidate_textptr (Transact-SQL)
Invalidates the specified in-row text pointer, or all in-row text pointers, in the transaction. sp_invalidate_textptr can be used only on in-row text pointers. These pointers are from tables that have the text in row option enabled.
Click this link

sp_lock (Transact-SQL)
Reports information about locks.
Click this link

sp_monitor (Transact-SQL)
Displays statistics about Microsoft SQL Server.
Click this link

sp_procoption (Transact-SQL)
Sets stored procedure for autoexecution. A stored procedure that is set to autoexecution runs every time an instance of SQL Server is started.
Click this link

sp_recompile (Transact-SQL)
Causes stored procedures and triggers to be recompiled the next time they are run.
Click this link

sp_refreshsqlmodule (Transact-SQL)
Updates the metadata for the specified nonschema-bound stored procedure, user-defined function, or view. Persistent metadata for these objects, such as data types of parameters, can become outdated because of changes to their underlying objects.
Click this link

sp_refreshview (Transact-SQL)
Updates the metadata for the specified non-schemabound view. Persistent metadata for a view can become outdated because of changes to the underlying objects upon which the view depends.
Click this link

sp_releaseapplock (Transact-SQL)
Releases a lock on an application resource.
Click this link

sp_rename (Transact-SQL)
Changes the name of a user-created object in the current database. This object can be a table, index, column, alias data type, or Microsoft .NET Framework common language runtime (CLR) user-defined type.
Click this link

sp_renamedb (Transact-SQL)
Changes the name of a database.
Click this link

sp_resetstatus (Transact-SQL)
Resets the status of a suspect database.
Click this link

sp_setnetname (Transact-SQL)
Sets the network names in sys.servers to their actual network computer names for remote instances of SQL Server 2005. This procedure can be used to enable execution of remote stored procedure calls to computers that have network names containing SQL Server identifiers that are not valid.
Click this link

sp_settriggerorder (Transact-SQL)
Specifies the AFTER triggers that are fired first or last. The AFTER triggers that are fired between the first and last triggers are executed in undefined order.
Click this link

sp_spaceused (Transact-SQL)
Displays the number of rows, disk space reserved, and disk space used by a table, indexed view, or SQL Server 2005 Service Broker queue in the current database, or displays the disk space reserved and used by the whole database.
Click this link

sp_tableoption (Transact-SQL)
Sets option values for user-defined tables. sp_tableoption can be used to control the in-row behavior of tables with varchar(max), nvarchar(max), varbinary(max), xml, text, ntext, or image columns.
Click this link

sp_unbindefault (Transact-SQL)
Unbinds, or removes, a default from a column or from an alias data type in the current database.
Click this link

sp_unbindrule (Transact-SQL)
Unbinds a rule from a column or an alias data type in the current database.
Click this link

sp_updateextendedproperty (Transact-SQL)
Updates the value of an existing extended property.
Click this link

sp_updatestats (Transact-SQL)
Runs UPDATE STATISTICS against all user-defined and internal tables in the current database.
Click this link

sp_validname (Transact-SQL)
Checks for valid SQL Server 2005 identifier names. All nonbinary and nonzero data, including Unicode data that can be stored by using the nchar, nvarchar, or ntext data types, are accepted as valid characters for identifier names.
Click this link

sp_who (Transact-SQL)
Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a specific user, or that belong to a specific session.
Click this link

Posted in SQL Server 2005 | Leave a comment

How to insert or add URL links inside the gridview?

How to insert or add URL links inside the gridview?

There are many ways to insert or add links inside a grid. There are many ways to display all the pages in your site in a gridview.

This is one way,

<asp:HyperLinkField DataTextField="Modules" HeaderText="Name" NavigateUrl='<% Bind("URL") %>' />

This the second way to do this,

<asp:TemplateField HeaderText="Name" SortExpression="Modules">
<ItemTemplate>
<asp:HyperLink ID="hlModules" runat="server" Text='<%# Bind("Modules") %>' />
                                                                        </ItemTemplate>                                                                   

</asp:TemplateField>

Then add this code in gridview RowCreated event,

if (e.Row.RowType == DataControlRowType.DataRow)
{
    HyperLink hl = (HyperLink)e.Row.FindControl("hlModules");
    hl.NavigateUrl = "MyPage.aspx";
}

But if you want to open the page in a new window or pop up. You need to put this code in RowDataBound event of the gridview and do like this,

if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = (HyperLink)e.Row.FindControl("hlModules");
switch(hl.Text)
{
case "FirstPage":
hl.NavigateUrl = "javascript:OpenFirstPage();";
break;                       

case "SecondPage":
hl.NavigateUrl = "javascript:OpenSecondPage();";
break;                       

 …

}
}

Of course you need to create the javascript to open a pop up window like this,

<script type="text/javascript" language="javascript">
var winArray = new Array()
function OpenFirstPage()
{
if (!winArray[0] || winArray[0].closed)
winArray[0] = window.open("FirstPage.aspx", "FirstPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");
else
winArray[0].focus();
}

function OpenSecondPage()
{
if (!winArray[0] || winArray[0].closed)
winArray[0] = window.open("SecondPage.aspx", "SecondPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");

else

winArray[0].focus();

}

</script>


You may refer to my other post or blog on how to open popup or close all popup windows.

Here are my references:
Link 0

Link 1
Link 2
Link 3
Link 3
Link 4
Link 5
Link 6

Link 7
Link 8
Link 9
Link 10
Link 11
Link 12
Link 13

Posted in ASP.NET 3.5 And C# 3.5, ASP.NET 3.5 And JavaScript, ASP.NEt And C# 3.5 And Javascript, C# 3.5 AND ASP.NET 3.5, JavaScript | Leave a comment

How to close all windows upon signout?

This solution might not be the exact solution to close all open windows, but it does close all windows upon clicking sign out.

First, you need to create a sign out button on your master page. Then put this code your click event of the button.

Here is the code:

Session.Clear();

Response.Redirect("~/LoginPage.aspx");

Second, You need to create a login page. I do not need to put the code for the login page. You can do that.

Third, You need to create javascript that will open each page.

Here is the javascript:

<script type="text/javascript" language="javascript">

var winArray = new Array()

function OpenFirstPage() {

if (!winArray[0] || winArray[0].closed)

winArray[0] = window.open("FirstPage.aspx", "FirstPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");

else

winArray[0].focus();

}

function OpenSecondPage() {

if (!winArray[1] || winArray[1].closed)

winArray[1] = window.open("SecondPage.aspx", "SecondPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");

else

winArray[1].focus();

}

function OpenThirdPage() {

if (!winArray[2] || winArray[2].closed)

winArray[2] = window.open("ThirdPage.aspx", "ThirdPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");

else

winArray[2].focus();

}

function SignOut()

{

if (winArray[0] == null)

OpenFirstPage();

winArray[0].close();

if (winArray[1] == null)

OpenSecondPage();

winArray[1].close();

if (winArray[2] == null)

OpenThirdPage();

winArray[2].close();

}

</script>

Fourth, You need to add attributes to your sign out and button.

Here is the code:

this.lnkUser.Attributes.Add("onclick", "javascript:OpenFirstPage()");

this.lnkTeams.Attributes.Add("onclick", "javascript: OpenSecondPage()");

this.lnkVolunteers.Attributes.Add("onclick", "javascript: OpenThirdPage()");

this.lnkLogout.Attributes.Add("onclick", "javascript:SignOut()");

References used:

Link 1

Link 2

Link 3

Link 4

Link 5

Link 6

Link 7

Link 8

Posted in ASP.NET 3.5, ASP.NET 3.5 And C# 3.5, ASP.NET 3.5 And JavaScript, C# 3.5, JavaScript | Leave a comment

How to do multiple popup window using ASP.NET 3.5 and AJAX Control and Javascript?

There are three ways to popup a new window. The first way to do popup window,

this.lnkNewWindow.Attributes.Add("onclick", "window.open('NewWindow.aspx', 'NewWindow', 'toolbar=no, menubar=no, directories=no, resizable=yes, scrollbar=yes');return false;");

this the second way to do popup window,

<asp:LinkButton ID="lnkNewWindow" runat="server" Text="New Window" onclick="javascript:openNewWindow();” />

Put this javascript inside script tag,

function OpenNewWindow()
{
window.open('NewWindow.aspx', 'NewWindow', 'toolbar=no, menubar=no, directories=no, resizable=yes, scrollbar=yes');
return false;
}

This is the third way to do popup window,

this.lnkNewWindow.Attributes.Add("onclick", "javascript:OpenNewWindow();");

To close this window just call window.close() like this,

this.btnClose.Attributes.Add("onclick", "window.close()");

If you are doing popup window that has functionality of exporting to pdf or excel with multiview control and updatepanel. You need to put postback trigger. Here is my link.

Here are my References for popup window:

Posted in ASP.NET 3.5 And JavaScript, C# 3.5, C# 3.5 AND ASP.NET 3.5, JavaScript | Leave a comment

How to export to pdf or excel in ASP.NET 3.5?

Here are my references for export to pdf or excel:
Reference 1
Reference 2
Reference 3
Reference 4
Reference 5
Reference 6

Posted in ASP.NET 3.5, Excel, PDF | 1 Comment

Five things you must do to lengthen PC life

This post is from this link.
Here are five simple things you must do to lengthen the life of your beloved computer.

Update Windows

Avoid skipping Windows Update if possible. As the updates are pushed from Microsoft’s server to your computer automatically, install the updates as soon as possible and restart your computer if necessary. While this may be a hassle at times, it does keep your computer safer and improve its stability.

Microsoft Security Essentials

Regardless of which operating system you are using, Windows, Mac or Linux, there are always viruses out there. Because Windows is the commonly used operating system in the world, you will need an antivirus software to be running in the background. Please do not try to run multiple antivirus softwares on the same system as this will lead to system instability.

Here’s the good news though, there’s no need to pay for an antivirus, for you have Microsoft Security Essentials to turn to. As a matter of fact, Microsoft Security Essentials is pretty great on its own. Findings from AV-Test.org shows it detects 98% of their enormous malware database, and AV-Comparatives.org found MSE to be one of only three products that did well at both finding and removing malware, including the leftovers. On top of that, they are the only free product to achieve an “Advanced+” rating – the top award for an anti-malware solution.

Nevertheless the technically inclined note that MSE does not incorporate fancy heuristics to detect viruses that aren’t already in the database. Whether this is a major weakness, it depends very much if you have the tendency to open files from untrusted sources. For the best defense against malware is safe browsing, with or without antivirus.

Back Up Your Hard Drive

Be it the simple Windows Backup or other automated offsite backup tool like Crashplan, backups are crucial for any computer user. And it is not just about maintenance, it’s about having access to your files when your computer stops showing any signs of life. And this is one of the most important maintenance you will have to carry out.

Clean Up Your Temporary Files

It is normal for Windows to have a lot of temporary files stored on your hard drive, mostly from your web surfing, and it is a good idea to clean these up regularly. A great tool for this job is CCleaner, and you can use this to clean up your PC manually or set up an automated schedule, keeping your computer free of all the temporary clutter.

Completely Uninstall Programs

While Windows’ Add/Remove Programs dialog is a useful feature, Revo Uninstaller is by far better. Not only does it remove all traces of an application from your computer, but it also helps you uninstall apps you can’t locate, in addition to managing your startup processes which can speed up your boot up and run smoother once you do.
Posted in Computer, Laptop, Windows 7 | Leave a comment

How to extract data from site?

Web scraping (also called Web harvesting or Web data extraction) is a computer software technique of extracting information from websites.
Here is the code that extract the content of a specific site,

WebClient wc = new WebClient();
string html = string.Empty;
MatchCollection matches;
string url = string.Empty;
int id = 0;
html = wc.DownloadString(urlPath).Replace("<html>", "").Replace("</html>", "").Replace("<!DOCTYPEHTML>", "").Replace("<head>", "").Replace("</head>", "").Replace("<script>", "").Replace("</script>", "");matches = Regex.Matches(html, "(.*?)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (destinationList == null)
destinationList = new List();
foreach (Match match in matches)
{
string matchUrl = match.Groups[1].Value;
//For internal links, build the url mapped to the base address
if (match.Groups[0].Value.Contains("travel/landing_page_hotels.cfm"))
{
url = MapUrl(urlPath, match.Groups[1].Value);
if (url.Length > 0)
{
destination = new clsDestinations();
id += 1;
destination.ID = id;
destination.Url = url;
destination.CityName = match.Groups[2].Value;
if (!destinationList.Exists(d => d.CityName == destination.CityName))
destinationList.Add(destination);
}
}
}

Once you have the data in your collection. Then you can save them one by one like this,

foreach(clsDestinations cy in destinationList)
{
if (!cityBll.CheckForDuplicateCity(cy, false))
result += cityBll.InsertCity(cy);
}

Here are the references that I have used:
web scraping
extract text

Posted in C# 3.5 | Leave a comment

How to Create a Simple Drop-Down List in MS Excel 2007?

this post is derive from this link. this can be in microsoft excel 2007.

1.
 Step 1

Click on the cell in the workbook where you want your drop-down list to appear. Cell A3 is active in the image to the left (click image to enlarge it).

2.
Step 2
Click the Data tab, and on the Data Tools menu, click on Data Validation. The Data Validation dialog box will appear.

3.
Step 3
On the Settings tab, below Allow, click the down arrow and select List.

4.
Step 4
For a simple list, type the items in the Source box in the order you want them to appear in the drop down, separating them by a comma as shown is the image. Click the OK button.

5.
Step 5
Now, at the insertion point, you can click the down arrow to display the options, clicking on one to select it.

References:

http://www.ehow.com/how_4535524_simple-dropdown-list-ms-excel.html#ixzz1R7FQFMg

Posted in Microsoft Excel 2007 | Leave a comment

Interview Cheat Sheet By Carole Martin

this article is from this link

Relax — a cheat sheet is not really cheating. It’s a checklist to make sure you stay focused before, during and after the interview. Creating a cheat sheet will help you feel more prepared and confident. You shouldn’t memorize what’s on the sheet or check it off during the interview. You should use your cheat sheet to remind you of key facts. Here are some suggestions for what you should include on it.
In the Days Before the Interview
• Draw a line down the center of a piece of paper. On the left side, make a bulleted list of what the employer is looking for based on the job posting. On the right side, make a bulleted list of the qualities you possess that fit those requirements.
• Research the company, industry and the competition.
• Prepare your 60-second personal statement.
• Write at least five success stories to answer behavioral interview questions (“Tell me about a time when…” or “Give me an example of a time…”).
• List five questions to ask the interviewer about the job, the company and the industry.
• Research salaries to determine your worth.
• Determine your salary needs based on your living expenses.
• Get permission from your references to use their names.
Prepare Your Interview Answers

Be ready to answer common interview questions such as these:
• Tell me about yourself.
• Why did you leave your last position, or why are you leaving your current position?
• What do you know about this company?
• What are your goals?
• What are your strengths and weaknesses?
• Why do you want to work here?
• What has been your most significant achievement?
• How would your last boss and colleagues describe you?
• Why should we hire you?
• What are your salary expectations?
Before You Go to the Interview
Do you look professional? Check yourself in the mirror; part of your confidence will come from looking good.
Carry these items to the interview:
• Several copies of your resume on quality paper.
• A copy of your references.
• A pad of paper on which to take notes, though notes are optional.
• Directions to the interview site.
Upon Arrival
• Arrive early — enter the building 10 minutes before your appointment.
• Review your prepared stories and answers.
• Go to the restroom and check your appearance one last time.
• Announce yourself to the receptionist in a professional manner.
• Stand and greet your interviewer with a hearty — not bone-crushing — handshake.
• Smile and maintain eye contact.
During the Interview
• Try to focus on the points you have prepared without sounding rehearsed or stiff.
• Relax and enjoy the conversation.
• Learn what you can about the company.
• Ask questions and listen; read between the lines.
• At the conclusion, thank the interviewer, and determine the next steps.
• Ask for the interviewer’s business card so you can send a follow-up letter.
After the Interview
• As soon as possible, write down what you are thinking and feeling.
• Later in the day, review what you wrote and assess how you did.
• Write an interview thank-you letter, reminding the interviewer of your qualities.

Posted in Job Hunting | Leave a comment

How to activate Windows 7?

How To Uninstall Windows 7 SP1?
Here are my references:

http://windows.microsoft.com/uninstallwindows7sp1

http://www.intowindows.com/how-to-uninstall-windows-7-sp1-service-pack-1/

http://www.ghacks.net/2011/02/23/how-to-uninstall-windows-7-service-pack-1/

How to Activate Windows 7 Online?
Here are my References:

http://www.sevenforums.com/tutorials/3408-activate-windows-7-online.html

http://www.kodyaz.com/articles/how-to-activate-windows-7.aspx

http://windows.microsoft.com/en-US/windows7/activate-windows-7-on-this-computer

http://www.online-tech-tips.com/windows-7/activate-windows-7-over-the-internet-or-by-phone/

http://www.techcular.com/how-to-activate-windows-7-online-using-product-keys/

How to activate windows 7 by telephone?
Here are my references:

http://www.kodyaz.com/articles/how-to-activate-windows-7-by-phone.aspx

http://www.sevenforums.com/tutorials/18715-activate-windows-7-phone.html

http://support.microsoft.com/kb/950929

http://www.technospot.net/blogs/how-to-activate-windows-7-on-phone/

http://www.askdrtech.com/solutions/post/How-To-Activate-Windows-7-by-Phone.aspx

How to Activate Windows 7 Manually – Windows 7 Activation Steps?

Here are my references:

http://www.kodyaz.com/articles/how-to-activate-windows-7.aspx

http://www.gocomputertraining.com/windows-7-activation.html

Windows Activation Technologies

http://www.gocomputertraining.com/windows-7-activator.html

Posted in Windows 7 | Leave a comment

How to upload and download files thru FTP Server?

How to upload and download files thru FTP Server?

I have use several references in creating this window application. I have somehow simplified it and extract codes from the references that I have used. There is only three buttons, they are upload, download and close. The upload button is used to copy file to ftp server. In short You are transferring or copying your local file to ftp server. The download button is used to get file from ftp server to your local folder or machine. The close button is used to close your application.

Here is what the application looks like, Here is my code,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace UploadDownloadFilesThruFTP
{
public partial class Form1 : Form
{
string ftpserverip;
string username;
string password;
string localFilename;
string targetFilename;
#region “Methods”
/// <summary>
/// Method to upload the specified file to the specified FTP Server
/// </summary>
/// <param name=”filename”>file full name to be uploaded</param>
private void Upload(string filename)
{
try
{
FileInfo fileInf = new FileInfo(filename);
if (ftpserverip == string.Empty)
ftpserverip = this.txtFtpServerIP.Text.Trim();
if (username == string.Empty)
username = this.txtUsername.Text.Trim();
if (password == string.Empty)
password = this.txtPassword.Text.Trim();
string uri = “ftp://” + ftpserverip + “/” + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(“ftp://” + ftpserverip + “/” + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(username, password);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Upload Error”);
}
}

private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be created.>>,
//fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
if (ftpserverip == string.Empty)
ftpserverip = this.txtFtpServerIP.Text.Trim();
if (username == string.Empty)
username = this.txtUsername.Text.Trim();
if (password == string.Empty)
password = this.txtPassword.Text.Trim();
FileStream outputStream = new FileStream(filePath + “\\” + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(“ftp://” + ftpserverip + “/” + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(username, password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private bool CheckFTPSettings()
{
bool isFtp = true;
if (this.txtFtpServerIP.Text.Length == 0)
{
MessageBox.Show(“FTP Server name or IP Address is required.”);
isFtp = false;
this.txtFtpServerIP.Focus();
}
else
{
if (this.txtUsername.Text.Length == 0)
{
MessageBox.Show(“Username is required.”);
isFtp = false;
this.txtUsername.Focus();
}
else
{
if (this.txtPassword.Text.Length == 0)
{
MessageBox.Show(“Password is required.”);
isFtp = false;
this.txtPassword.Focus();
}
}
}
return isFtp;
}
#endregion

public Form1()
{
InitializeComponent();
ftpserverip = string.Empty;
username = string.Empty;
password = string.Empty;
localFilename = string.Empty;
targetFilename = string.Empty;
}

private void Form1_Load(object sender, EventArgs e)
{
this.txtFtpServerIP.Text = “ftp.converged.net.au”;
this.txtUsername.Text = “arnold”;
this.txtPassword.Text = “passw0rd”;
}

private void btnUpload_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog files = new OpenFileDialog();
files.ShowDialog();
if (files.SafeFileName != string.Empty)
localFilename = files.FileName;
else
{
MessageBox.Show(“Please choose a file to upload.”);
return;
}
if (CheckFTPSettings())
Upload(localFilename);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void btnDownloadFile_Click(object sender, EventArgs e)
{
try
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
localFilename = ofd.SafeFileName;
if (CheckFTPSettings())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
Download(fbd.SelectedPath, localFilename);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}

}

private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
  Here are my references that I have used in this blog:

Code Project

C# Corner

Code Guru

MSDN – Microsoft

Ondotnet

Posted in C# 3.5, FTP Server | Leave a comment

My new Lenovo Z460 Laptop

I just bought Lenovo Ideapad Z460 at Lenovo (SM Megamall) which cost 34, 800 Php (less 3,000 php cash basis plus 1,900 php 2 GB RAM) – June 19, 2011.

Here are the specifications:

Processor & Cache Memory Intel Core i5-460M Processor with

  • Intel® Turbo Boost Technology
  • Intel® Hyper-Threading Technology

(3MB L3 cache, 2.53 GHz with Turbo Boost up to 2.8 GHz, DDR3 1066 MHz, 35W), supporting Intel® 64 architecture, Intel® Smart Cache

Operating System Free Dos (No Window OS Installed)
Main Memory 2GB DDR3 + 2GB DDR3 (1900 Php additional)
Display 14″ WXGA LED(1366×768)
Video Graphics & Memory Nvidia GeForce 310M 1GB DDR3
Hard Drive 2.5″ 9.5mm SATA
500GB HDD 5400rpm
Optical Drive 5.25″ , 12.7mm
Dual Layer Multiburner Drive (DVDRW)
Video Camera 1.3MP Web Camera with Face Recognition
Audio Dolby® Home Theater™ 2 Ceritification 2 x 2W stereo speaker
Fax/Modem/LAN/WLAN  

Realtek 10/100 Mbps LAN, Intel WiFi Link 5100a/g/n, Built-in Bluetooth

I/O 3 x USB 2.0 ports, 1* 34mm Express Card slot, RJ45, VGA, Mic-In, Headphone, 5-in-1 Multi-card Reader (SD,SD Pro/XD/MMC/MS,MS Pro), HDMI
Battery Pack & Life 6 Cell Li-ion Battery
Weight 2.1 Kgs.
Warranty & e-support 1-year Regional Carry-in Warranty (ASEAN + China)

I will soon make a review in this post. To see what I have found out. My first impression is that the design is bad. the keyboard and the IO ports (USB, and other) is like my previous ASUS A8JR. The difference is that the CPU is now i5-460M, 4 CPU instead of 2 CPU, the HDD space is much bigger than my previous laptop which is just 120 GB. It has veriface which uses face recognition to log into the system.

Posted in Accent Micro, Intel Core i5-460M, Lenovo Z460 | Leave a comment

How to create simple dynamic window form application?

I have created a window form that will generate two textbox, one combobox, one datepicker, and four label. This form does not connect to any database. The purpose of this application is to show how to create controls at runtime.

Here is my code:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace DynamicWindowsFormsApplication

{

    public class Person

    {

        string _name;

        string _address;

        string _gender;

        DateTime _dateOfBirth;

        public Person()

        {

            _name = string.Empty;

            _address = string.Empty;

            _gender = string.Empty;

            _dateOfBirth = new DateTime();

        }

        public string Name

        {

            get

            {

                return _name;

            }

            set

            {

                if (_name != value)

                    _name = value;

            }

        }

        public string Address

        {

            get

            {

                return _address;

            }

            set

            {

                if (_address != value)

                    _address = value;

            }

        }

        public string Gender

        {

            get

            {

                return _gender;

            }

            set

            {

                if (_gender != value)

                    _gender = value;

            }

        }

        public DateTime DateOfBirth

        {

            get

            {

                return _dateOfBirth;

            }

            set

            {

                if (_dateOfBirth != value)

                    _dateOfBirth = value;

            }

        }

    }

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            this.ControlBox = false;

            int x = 0;

            int y = 0;

            Point pt = new Point();

            pt.X = 10;

            pt.Y = 10;

            x = pt.X;

            y = pt.Y;

            Label lbl = new Label();

            lbl.Name = “lblName”;

            lbl.Location = pt;

            lbl.Text = “Name:”;

            lbl.TextAlign = ContentAlignment.TopRight;

            this.Controls.Add(lbl);

            TextBox txt = new TextBox();

            txt.Name = “txtName”;

            txt.Width = 250;

            pt = new Point(lbl.Width + 10, 10);

            x = pt.X;

            y = pt.Y;

            txt.Location = pt;

            this.Controls.Add(txt);

            y = txt.Height + 15;

            lbl = new Label();

            lbl.Name = “lblAddress”;

            pt = new Point(10,y);

            lbl.Location = pt;

            lbl.Text = “Address:”;

            lbl.TextAlign = ContentAlignment.TopRight;

            this.Controls.Add(lbl);

            txt = new TextBox();

            txt.Name = “txtAddress”;

            txt.Width = 250;

            pt = new Point(lbl.Width + 10, y);

            txt.Location = pt;

            this.Controls.Add(txt);

            y += txt.Height + 5;

            lbl = new Label();

            lbl.Name = “lblGender”;

            lbl.Text = “Gender:”;

            lbl.TextAlign = ContentAlignment.TopRight;

            pt = new Point(10, y);

            lbl.Location = pt;

            this.Controls.Add(lbl); 

            x = lbl.Width + 10;

            ComboBox cbo = new ComboBox();

            cbo.Name = “cboGender”;

            cbo.Width = 250;

            cbo.Items.Add(“Male”);

            cbo.Items.Add(“Female”);

            pt = new Point(x, y);

            cbo.Location = pt;

            this.Controls.Add(cbo);

            y += cbo.Height + 5;

            lbl = new Label();

            lbl.Name = “lblDateofBirth”;

            lbl.Text = “Date of Birth:”;

            lbl.TextAlign = ContentAlignment.TopRight;

            lbl.Location = new Point(10, y);

            this.Controls.Add(lbl);

            DateTimePicker picker = new DateTimePicker();

            picker.Name = “dtpDateOfBirth”;

            picker.Width = 250;

            picker.Location = new Point(lbl.Width + 10, y);

            this.Controls.Add(picker);

            y += picker.Height + 5;

            List<Person> personList = new List<Person>();

            Button btn = new Button();

            btn.Name = “btnSave”;

            btn.Text = “Save”;

            btn.TextAlign = ContentAlignment.TopRight;

            btn.Location = new Point(10, y);

            btn.Click += new EventHandler(btnSave_Click);

            this.Controls.Add(btn);

            x = btn.Width + 10;

            btn = new Button();

            btn.Name = “btnReset”;

            btn.Text = “Reset”;

            btn.TextAlign = ContentAlignment.TopLeft;

            btn.Location = new Point(x, y);

            btn.Click += new EventHandler(btnReset_Click);

            this.Controls.Add(btn); 

        }

        void btnReset_Click(object sender, EventArgs e)

        {

            try

            {

                foreach (Control c in this.Controls)

                {

                    if (c.GetType() == typeof(TextBox))

                    {

                        ((TextBox)c).Text = string.Empty;

                    }

                    if (c.GetType() == typeof(ComboBox))

                    {

                        ((ComboBox)c).SelectedIndex = -1;

                    }

                    if (c.GetType() == typeof(DateTimePicker))

                    {

                        ((DateTimePicker)c).Text = string.Empty;

                    }

                }

            }

            catch (System.Exception ex)

            {

                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);

            }

        }

        void btnSave_Click(object sender, EventArgs e)

        {

            try

            {

                TextBox txt = new TextBox();

                ComboBox cbo = new ComboBox();

                DateTimePicker pick = new DateTimePicker();

                Person _person = new Person();

                foreach (Control c in this.Controls)

                {

                    if (c.GetType() == typeof(TextBox))

                    {

                        txt = new TextBox();

                        txt = (TextBox)c;

                        if (txt.Name.Contains(“Name”))

                            _person.Name = txt.Text.Trim();

                        if (txt.Name.Contains(“Address”))

                            _person.Address = txt.Text.Trim();

                    }

                    if (c.GetType() == typeof(ComboBox))

                    {

                        cbo = new ComboBox();

                        cbo = (ComboBox)c;

                        if (cbo.Name.Contains(“Gender”))

                            _person.Gender = cbo.SelectedItem.ToString();

                    }

                    if (c.GetType() == typeof(DateTimePicker))

                    {

                        pick = new DateTimePicker();

                        pick = (DateTimePicker)c;

                        if (pick.Name.Contains(“DateOfBirth”))

                            _person.DateOfBirth = Convert.ToDateTime(pick.Value);

                    }

                }

                MessageBox.Show(” Name: ” + _person.Name + Environment.NewLine + ” Address: ” +  _person.Address + Environment.NewLine + ” Gender: ” + _person.Gender + Environment.NewLine + ” Date of Birth: ” + _person.DateOfBirth.ToString());

            }

            catch (System.Exception ex)

            {

                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);

            }

        }

    }

}

Posted in C# 3.5, Visual Studio 2008 | Leave a comment

How to do partition in Windows 7?

Many of us looking for answer or solutions on how to partition in windows 7. Here are the references that I have used:

http://www.sevenforums.com/tutorials/2674-partition-volume-create-new.html
http://windows.microsoft.com/en-US/windows7/Create-and-format-a-hard-disk-partition
http://windows.microsoft.com/en-US/windows7/Delete-a-hard-disk-partition
http://windows.microsoft.com/en-us/windows7/Can-I-repartition-my-hard-disk
http://www.geeksdo.com/capture-unallocated-space-windows-7.html
http://www.techsupportforum.com/forums/f217/unallocated-space-problem-425998.html
http://forum.easeus.com/viewtopic.php?t=19839&sid=4cc22cfb59fe8c7589dd29df2f30b780
http://www.partition-tool.com/easeus-partition-manager/convert-dynamic-disk-to-basic-disk.htm
http://www.todo-backup.com/products/comparison.htm
http://www.todo-backup.com/products/features/backup-drive-and-partition.htm
http://forum.easeus.com/viewtopic.php?t=18196
http://forum.easeus.com/viewtopic.php?t=18511

Posted in Partition, Windows 7 | Leave a comment

Lenovo Service Center in the Philippines

Phone: 1800 111 00724
Hours of operation: Monday to Friday, 9:00am – 6:00pm Saturday 9:00 AM to 3:00 PM

Commercial / Key Accounts Customers Inquiries: 1 800 1 601 0035 (ext: 9015)

Mailing address:
Lenovo (Singapore) Pte Ltd. – Philippines
Unit 15-A,15th Floor,
Citibank Tower,
Paseo de Roxas,
Makati City 1200.

6 months extended service warranty
MSI-ECS Phils., Inc./DIGICare Service Center
G/F, Shop #10
PHILPLANS CORPORATE CENTER
1012 North Triangle Drive
Bonifacio Global City, Taguig City
(Along Kalayaan Avenue)

here is the map:
Service center in Metro Manila, you may refer to the link below for other areas.
Accent Micro Products, Inc. – Head Office Rm. 607 16/F East Tower Phil. Stock Exchange Tower Ortigas Center Pasig city, Metro Manila Metro Manila
Phone:(+632) 323-4766 / (+632) 323-2168 loc 2225
Office/Store hours: Mon-Fri (except Public Holidays) 8:30am – 6:30pmAccent Micro Products, Inc. – Warehouse 259 C. Raymundo, Ave, May Bunga Pasig City Metro Manila
Phone:(+632) 323-2168 (+632) 640-9256
Office/Store hours: Mon-Fri (except Public Holidays) 8:30am – 6:30pmAdvance Solutions, Inc. 3F 302 PPL Bldg., UN Ave. corner San Marcelino St., Paco, Manila City Metro Manila
Phone:(+632) 526-3935; (+632) 526-3780
Fax:(+632) 526-4116
Office/Store hours: Mon-Sat (except Public Holidays) 9:00am – 6:00pm

Asianic Distributors Inc. – Acrotech Champaca St. Ups 4 868 Sucat Paranaque Near Sucat Exit Metro Manila
Phone:(+632) 823-2528
Office/Store hours: Mon-Sat 8:30-5:30 (except public holidays)

Asianic Distributors Inc. – Head Office 1503 Cristobal St. Corner Dimasalang Sampaloc Manila Metro Manila
Phone:(+632) 583-3563; (+632) 415-8141; (+632) 415-8241;
Office/Store hours: Mon-Sat 8:30am-6:30pm (except public holidays)

Asianic Distributors Inc. – Kenctucky # 18 E Porto (Formerly Kentucky) San Fransisco Del Monte Quezon City, Metro Manila
Phone:(+632) 415-8141; (+632) 415-8241
Office/Store hours: Mon-Sat 8:30-5:30 (except public holidays)

Columbia Technologies, Inc. 1136-1146 J. Nakpil St., Malate II, Manila City Metro Manila
Phone:(+632) 524-0393 / (+632) 524-0394 / (+632) 400-7981
Fax:(+632) 522-6989
Office/Store hours: Mon-Fri (except Public Holidays) 7.30am – 5.30pm

Complink E-Hub Muntinlupa City 3/F Alabang Town Center Muntinlupa City Metro Manila
Phone:(+632) 775-0140 / (+632) 775-0141
Fax:(+632) 775-014
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink E-Hub Alabang Alabang Town Center Alabang Muntinlupa City Metro Manila
Phone:(+632) 775-0140
Office/Store hours: Mon-Fri (except Public Holidays) 7.30am – 5.30pm

Complink E-Hub Makati City G/F Park Square 1, Makati City Metro Manila
Phone: (+632) 818-4856; (+632) 752-8635
Fax: (+632) 752-8635
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink E-Hub, Eastwood 2/F Cyber Mall Eastwood City Cyberpark Metro Manila
Phone:(+632) 687-3212
Fax: (+632) 687-3212
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing – Head Office Unit 1204, 12th Floor Robinsons Equitable Tower Adb Avenue, Ortigas Pasig City Metro Manila
Phone: (+632) 687-1234; (+632) 687-3160
Fax: (+632) 395-3535
Office/Store hours: Mon-Fri (except Public Holidays) 7.30am – 5.30pm

Complink Marketing – SM Megamall Bldg. B Level 4 Cyberzone, Mandaluyong City Metro Manila
Phone: (+632) 631-9901; (+632) 631-6958
Fax: (+632) 637-3988
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing Galleria Level III Expansion Mall Robinsons Galleria EDSA Mandaluyong City Metro Manila
Phone: (+632) 632-9896 to 97
Fax: (+632) 632-9896
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing- Parksquare G/F Park Square 1, Makati City Metro Manila
Phone: (+632) 893-1489; (+632) 893-1491; (+632) 893-1493
Fax: (+632) 893-1493
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing- SM Mall of Asia 204 2nd flr. North, SM Mall of Asia Pasay City Metro Manila
Phone:(+632) 556-0722 to 23
Fax: (+632) 556-0722
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing- SM North Edsa 5th Floor, SM North Edsa Annex, Q.C Metro Manila
Phone: (+632) 441-1781 to 83
Fax: (+632) 441-1781
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Complink Marketing -SM South Mall 3/F SM Southmall Las Piñas City Metro Manila
Phone: (+632) 801-9908; (+632) 802-3977
Fax: (+632) 802-3977
Office/Store hours: Mon-Sun 10:00am – 10:00pm (including Public Holidays)

Complink Marketing- Trinoma 2077 k Trinoma North Avenue Edsa Quezon City Metro Manila
Phone: (+632) 901-5586 to 87
Fax:(+632) 901-5587
Office/Store hours: Mon-Sun 10:00am – 10:00pm (except Public Holidays)

Compuserve Technologies Inc. #35 San Antonio St. San Francisco Del Monte Quezon City Metro Manila
Phone: (+632) 371-6868 loc. 110
Fax: (+632) 371-6868 loc. 133
Office/Store hours: Mon-Fri 8:00am – 6:00pm Saturday 8:30 am – 3:00pm (except Public Holidays)

First Data Corp. 3F Citybank Center, 8741 Paseo De Roxas, Makati City Metro Manila
Phone: (+632) 893 6657
Fax: (+632) 815 8650
Office/Store hours: Mon-Fri (except Public Holidays) 8.30am – 5.30pm

GigaHertz Computer Systems- Head Office 426 P. Casal Cor. Balmes Quiapo Manila city, Metro Manila Metro Manila
Phone:(+632) 733-9904 Loc.204, (+632) 735-9148
Fax: (+632) 733-9904; (+632) 735-9148
Office/Store hours: Mon-Fri (except Public Holidays) Mon-Sat 9:00am-6:00pm

GigaHertz Computer Systems- Robinson Malate Level III Stall#035-2036 Robinson’s Place Malate Ermita Manila Metro Manila
Phone:(+632) 521-4163
Fax: (+632)521-4163
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Cubao Unit 21 SM cubao #1109 Araneta Center Cubao Quezon city Metro Manila
Phone: (+632) 911-0409
Fax: (+632) 911-0409
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Mall of Asia Unit 209 North Parking SM Mall of Asia Pasay City Metro Manila
Phone: (+632) 556-0538
Fax: (+632) 556-0538
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Manila Cyberzone #10 Cyberzone Area SM Manila Metro Manila
Phone: (+632) 525-1515
Fax: (+632) 525-1515
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Marikina Cyberzone SM city Marikina Kalumpang Marikina city Metro Manila
Phone: (+632) 525-1514
Fax: (+632) 477-1844
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Megamall 4th flr. SM Megamall EDSA Corner Julia Vargas Ave., Mandaluyong city Metro Manila
Phone: (+632) 470-2070
Fax: (+632) 470-2070
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM San Lazaro Unit 334 3rd Flr SM City San Lazaro AH Lacson St. Sta Cruz Manila Metro Manila
Phone: (+632) 786-2601
Fax: (+632) 786-2601
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

GigaHertz Computer Systems- SM Virramall Unit 317 VMall Greenhills Shopping Center San Jaun Metro Manila Metro Manila
Phone: (+632) 727-7842
Fax: (+632) 727-7842
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 10:00pm

IBRAINS Technologies Corp- Paranaque Branch Parañaque- 7095 Escudo Lane, Villanueva Village, Paranaque City Metro Manila
Phone: (+63)918-685-2647 / (+63)922-816-9363 / (+6344) 662-1339 / (+6344) 796-0180
Fax: (+6344) 796-0180 / (+6344) 662-1339
Office/Store hours: Mon-Fri (except Public Holidays) 8.00am – 5.00pm

IBRAINS Technologies Corp- Sta. Mesa Branch Sta.Mesa- 600 Roces St., Sta. Mesa, Manila Metro Manila
Phone: (+63)918-685-2647 / (+63)922-816-9363 / (+6344) 662-1339 / (+6344) 796-0180
Fax: (+6344) 796-0180 / (+6344) 662-1339
Office/Store hours: Mon-Fri (except Public Holidays) 8.00am – 5.00pm

Innovista Technologies, Inc. 5F ATCO Bldg., 137 Aurora Blvd., San Juan, Metro Manila Metro Manila
Phone: (+632) 994-3497 (+632) 994-3693
Office/Store hours: Mon-Fri (except Public Holidays) 8.00am – 6:00pm

Lenove Concept Store- SM Megamall Branch Lenovo Megamall – Unit 435 4/F Bldg. B Cyberzone Area, SM Megamall, Mandaluyong City Metro Manila
Phone: (+632) 631-8147; (+632) 632-7432
Office/Store hours: 7 days a week (including Public Holidays) 10:00am – 9:00pm

Lenovo Concept Store- Mall of Asia 2nd floor north wing sm mall of asia, pasay city Metro Manila
Phone: (+632) 556-1537
Office/Store hours: Mon-Sun (except Public Holidays) 10:00am-10:00 pm

Lenovo Concept Store- SM North Edsa SM North EDSA, Quezon City Metro Manila
Phone: (+632) 441-1390 / (+632) 441-1390
Fax: (+632) 441-1390
Office/Store hours: 7 days a week (including Public Holidays) 10.00am – 10:00pm

Micro Image International Corporation Unit 101 10F Legaspi Suites Bldg., Salcedo City, Legaspi Village, Makati City Metro Manila
Phone: (+632) 840-4050 to 51 (+632) 840-4324; (+632) 752-4525 to 29
Fax: (+632) 894-2590 (+632) 840-4050 local 141
Office/Store hours: Mon-Fri (except Public Holidays) 8.00am – 5.30pm

Micro Pacific Technologies & Systems Corporation Unit 2A Gervacia Corporate Center, 152 Amorsolo St., Legaspi Village, Makati City Metro Manila
Phone: (+632) 840-4563 local 115 to 101
Fax: (+632) 894-5860 (+632) 894-5863
Office/Store hours: Mon-Fri (except Public Holidays) 8.30am – 5.30pm

Microbase, Inc. 5F Casmer Bldg., 195 Salcedo St., Legaspi Village, Makati City Metro Manila
Phone: (+632) 813- 7603 local 191
Fax: (+632) 817-0258 / (+632) 813-7603 local 158
Office/Store hours: Mon-Fri (except Public Holidays) 9:00am -6:00pm

Northgate Technologies, Inc. M-VIII The Gallery, Amorsolo St., Legaspi Village, Makati City Metro Manila
Phone: (+632) 724-4410 / (+632) 892-7620 / (+632) 844-6477 / (+632) 843-5382 / (+632) 815- 6221 / (+632) 893- 2434 / (+632 )893-7514 / (+632 ) 893-7464 / (+632) 893-7154 / (+632 ) 893-7454
Fax: (+632) 722-0104
Office/Store hours: Mon-Fri (except Public Holidays) 7.30am – 5.30pm

The Computer Authority – Cubao Unit 001 LGF Cyberzone SM Cubao Bldg. Brgy. Socorro, Cubao Quezon City Metro Manila
Phone:(+632) 911-2970
Fax:(+632) 911-2970
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Eton Unit UG59-UGF E-Life @ ETON Cyberpod Corinthian, Ortigas Ave., near corner EDSA Brgy. Ugong Norte Q.C. Metro Manila
Phone: (+632) 470-7844
Fax: (+632) 470-7844
Office/Store hours: Mon-Sun (including Public Holidays) 11:00-8:00pm

The Computer Authority – Filinvest 3F Festival Supermall, Filinvest Corporate City, Alabang Metro Manila
Phone: (+632) 850-3759
Fax: (+632) 850-3711
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Futurelink 5/F Unit 525C Annex 1, SM City North Edsa Brgy. Sto.Cristo, Quezon City Metro Manila
Phone: (+632) 441-1779
Fax: (+632) 441-1779
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Mall of Asia 2F SM Central Business Park Bay City Pasay City Metro Manila
Phone: (+632) 556-4965
Fax: (+632) 556-4965
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Marikina G/F Cyberzone SM City Marikina Marcos Highway, Marikina City Metro Manila
Phone: (+632) 477-1843
Fax: (+632) 477-1843
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Megamall 4F Cyberzone Bldg. B SM Megamall, Mandaluyong City Metro Manila
Phone: (+632) 633-1594
Fax: (+632) 634-2437
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – North Edsa 5/F Unit 507 Annex 1, SM City North Edsa Brgy. Sto.Cristo, Quezon City Metro Manila
Phone: (+632) 441-1376
Fax: (+632) 441-1376
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Quad Shop 28, Quad Park Square 1, Ayala Commercial Center, Makati City Metro Manila
Phone: (+632) 810-5090
Fax: (+632) 810-6766
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Sta. Lucia 3F Sta. Lucia East Grandmall, cor. Felix Ave., Marcos Highway Cainta, Rizal Metro Manila
Phone: (+632) 681-7334
Fax: (+632) 579-8819
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

The Computer Authority – Virramall 3/F Unit V-368 V-Mall Greenhills Shopping Center, Greenhills San Juan Metro Manila
Phone: (+632) 584-5078
Fax: (+632) 584-5078
Office/Store hours: Mon-Sun (including Public Holidays) 9:30am – 9:00pm

Villman- Mall of Asia 2162(MM) SM Mall of Asia, SM Central Business Park Bay City, Pasay City Metro Manila
Phone: (+632) 556 1537
Office/Store hours: Mon-Sun (except Public Holidays) 10:00am-10:00 pm

Villman- Marikina 119 Annex A. SM City Marikina, Marcos Highway Calumpang, Marikina City Metro Manila
Phone: (+632)799-6888
Fax: (+632)799-6888
Office/Store hours: Mon-Sun (except Public Holidays) 10:00am – 9:45:pm

Zenshin Systems Corporation 25 General Roxas St., Brgy. San Jose, Quezon City Metro Manila
Phone: (+632) 366-9395 / (+632) 365-0536
Fax: (+632) 363-1679
Office/Store hours: Mon-Fri (except Public Holidays) 8.00am – 5.30pm

Reference Links:

http://www-307.ibm.com/pc/support/site.wss/document.do?lndocid=MIGR-66653#phillipines

Posted in Lenovo, Lenovo Service Center, Service Center | Leave a comment

ASUS Service Center in the Philippines

ASUS Philippine Call Hotline:1800-1441-0573 (10:00-21:00 Mon. ~ Fri.)
Please call:+63-(2)-636-8504 if you use mobile phone.

ASUS Authorized Service Center
Address: 7185 Export Ave cor Chino Roces Ave., Makati City
Business Hours: 8:00am-6:00pm (Mon-Fri) 9:00am-12:00nn (Sat)
Phone: 63 (2) 812 – 8976

Address: SM Megamall 4th Floor Cyberzone Bldg B Mandaluyong City
Business Hours: 10:00am-9:00pm (Sun- Thurs) 10:00am-10:00pm (Fri-Sat)
Phone: 63 (2) 638-2955

Address: 3/F Gilmore IT Center Bldg., #8 Gilmore Ave., cor. 1st Street, New Manila, Quezon City
Business Hours: 10:00am-7:00pm (Mon-Sun)
Phone: 63 (2) 994-3696

Address: Unit G, Gilmore Commercial Plaza, #10 Gilmore Avenue, New Manila Quezon City
Business Hours: 10:00am-7:00pm (Mon-Sat)
Phone: 63 (2) 721 – 9102 /6

Address: 4th Level VMALL Plaza Greenhills, San Juan, MM
Business Hours: 10:00am-8:00pm (Mon-Sun)
Phone: 63 (2) 584 – 2612

Address: Main Bldg. Junquera Ext. Cebu City
Business Hours: 9:00am-6:00pm (Mon-Fri)
Phone: 63 (32) 242 – 2227

Address: Stall 232B North Wing 272 2nd Floor Cebu
Business Hours: 10:00am-9:00pm(Mon-Sun)
Phone: 63 (32) 234 – 0219

Address: E-14 J. King Warehouse Complex Herman Cortes, Mandaue City
Business Hours: 8:30am-6:00pm (Mon-Fri) 9:00am-12:00nn (Sat)
Phone: 63 (32) 422 – 7510

Posted in ASUS, ASUS Service Center, Service Center | Leave a comment

How to create code generator for your data objects, data access layer and business access layer?

This post of mine shows how I create DAL, BAL, Data entity objects, interface. This code generator will generate code for this .cs file. First, this is how it looks like when you are creating DAL, Second, this is how it looks like when you are creating BAL, Third, this is how it looks like when you are creating data entity objects, Fourth, this is how it looks like when you are creating the interface, Here is the code,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace CSharpCodeGenerator
{
public partial class CodeGenerator : Form
{
StringBuilder sb;
string connstring = “Data Source=DEV-ARNOLD;Initial Catalog=TestDb;User ID=sa;Password=passw0rd;”;
SqlConnection conn;
SqlDataReader reader;
string dal;
string data;
string business;
string tablename;
string ConString;
string filename;
DataTable dt;
DataSet ds;
List tableList;
string foreign;
List foreignList;
string table;
string className;

public CodeGenerator()
{
InitializeComponent();
sb = new StringBuilder();
conn = new SqlConnection(connstring);
if (conn.State == ConnectionState.Closed)
conn.Open();
dal = “TestDataLayer”;
data = “TestDataEntity”;
business = “TestBusinessLayer”;
ConString = “TestSqlConnectionString”;
dt = new DataTable();
ds = new DataSet();
tableList = new List();
foreign = string.Empty;
foreignList = new List();
table = string.Empty;
className = string.Empty;
RetrieveAllTables();
PopulateGrid();
PopulateNamespaceList();
if (table != string.Empty)
tablename = table.Substring(3);
}

private void ResetEntry()
{
sb = new StringBuilder();
this.dgvField.DataSource = null;
this.txtGeneratedCode.Text = string.Empty;
}

private void PopulateGrid()
{
try
{
if (table == string.Empty)
return;
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = “select column_name AS ColumnName, data_type + case isnull(character_maximum_length,”) when ” then ” else ‘(‘ + cast (character_maximum_length AS varchar(6)) + ‘)’ end AS DataType, case is_nullable when ‘YES’ then ‘null’ else ‘not null’ end AS Nullable from information_schema.columns where table_name = ‘” + this.cboTables.Text.Trim() + “‘ order by ordinal_position”;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
reader.Close();
reader = cmd.ExecuteReader();
dt = new DataTable(“information_schema.columns”);
ds = new DataSet();
ds.Tables.Add(dt);
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]);
this.dgvField.DataSource = ds.Tables[0];
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void RetrieveAllTables()
{
try
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = “select distinct name from sysobjects where xtype=’U'”;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
reader = cmd.ExecuteReader();
this.cboTables.Items.Clear();
string select = string.Empty;
while (reader.Read())
{
this.cboTables.Items.Add(reader[0]);
select = Convert.ToString(reader[0]).Substring(3);
if (tableList == null)
tableList = new List();
if (tableList.Count == 0)
tableList.Add(select);
else
if (!tableList.Contains(select))
tableList.Add(select);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
finally
{
reader.Close();
}
}

private void RetrieveForeignKeyList()
{
try
{
RetrieveAllTables();
List list = new List();
foreach (DataRow r in ds.Tables[0].Rows)
{
foreign = Convert.ToString(r[0]).Replace(tablename, “”);
list.Add(foreign);
}
foreach (string f in list)
{
foreach (string s in tableList)
{
if (f.Contains(s))
{
foreign = s;
foreignList.Add(foreign);
}
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void PopulateNamespaceList()
{
try
{
this.cboNamespace.Items.Clear();
this.cboNamespace.Items.Add(dal);
this.cboNamespace.Items.Add(data);
this.cboNamespace.Items.Add(business);
this.cboNamespace.Items.Add(“Interface”);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void GenerateCode(string name)
{
try
{
string var = string.Empty;
if (table != string.Empty)
tablename = table.Substring(3);
RetrieveForeignKeyList();
ResetEntry();
PopulateGrid();
if (dal == name)
{
sb.Append(“using System;”);
sb.Append(Environment.NewLine + “using System.Collections.Generic;”);
sb.Append(Environment.NewLine + “using System.Text;”);
sb.Append(Environment.NewLine + “using System.Data;”);
sb.Append(Environment.NewLine + “using System.Data.SqlClient;”);
sb.Append(Environment.NewLine + “using System.Configuration;”);
sb.Append(Environment.NewLine + “using ” + data + “;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “namespace ” + dal);
sb.Append(Environment.NewLine + “{“);
filename = “cls” + tablename + “DAL”;
sb.Append(Environment.NewLine + “\t public class ” + filename + “: I” + tablename);
sb.Append(Environment.NewLine + “\t {“);
sb.Append(Environment.NewLine + “\t\t SqlConnection sqlConn;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public cls” + tablename + “DAL()”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[" + "\"TestSqlConnectionString\"" + "].ConnectionString);”);
sb.Append(Environment.NewLine + “\t\t\t sqlConn.Open();”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Insert” + tablename + “(” + tablename + “Entity ” + tablename.ToLower() + “)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t int result = 0;”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spInsert” + tablename + “\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
foreach (DataRow rw in ds.Tables[0].Rows)
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + Convert.ToString(rw[0]) + “\”, ” + tablename.ToLower() + “.” + Convert.ToString(rw[0]) + “);”);
sb.Append(Environment.NewLine + “\t\t\t\t result = cmd.ExecuteNonQuery();”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return result;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Update” + tablename + “(” + tablename + “Entity ” + tablename.ToLower() + “)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t int result = 0;”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spUpdate” + tablename + “\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
foreach (DataRow rw in ds.Tables[0].Rows)
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + Convert.ToString(rw[0]) + “\”, ” + tablename.ToLower() + “.” + Convert.ToString(rw[0]) + “);”);
sb.Append(Environment.NewLine + “\t\t\t\t result = cmd.ExecuteNonQuery();”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return result;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Delete” + tablename + “(int ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t int result = 0;”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spDelete” + tablename + “\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + tablename + “Id” + “\”, ” + tablename.ToLower() + “Id);”);
sb.Append(Environment.NewLine + “\t\t\t\t result = cmd.ExecuteNonQuery();”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return result;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public ” + tablename + “Entity Retrieve” + tablename + “ById(int ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t ” + tablename + “Entity ” + tablename.ToLower() + ” = new ” + tablename + “Entity();”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spGet” + tablename + “ById\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + tablename + “Id\”, ” + tablename.ToLower() + “Id);”);
sb.Append(Environment.NewLine + “\t\t\t\t using (SqlDataReader dr = cmd.ExecuteReader())”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t while (dr.Read())”);
sb.Append(Environment.NewLine + “\t\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t ” + tablename.ToLower() + ” = Load” + tablename + “Entity(dr);”);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t break;”);
sb.Append(Environment.NewLine + “\t\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public ” + tablename + “Entity Retrieve” + tablename + “ByName(string ” + tablename.ToLower() + “Name)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t ” + tablename + “Entity ” + tablename.ToLower() + ” = new ” + tablename + “Entity();”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spGet” + tablename + “ByName\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + tablename + “Name\”, ” + tablename.ToLower() + “Name);”);
sb.Append(Environment.NewLine + “\t\t\t\t using (SqlDataReader rd = cmd.ExecuteReader())”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t while (rd.Read())”);
sb.Append(Environment.NewLine + “\t\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t ” + tablename.ToLower() + ” = Load” + tablename + “Entity(rd);”);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t break;”);
sb.Append(Environment.NewLine + “\t\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public List Retrieve” + tablename + “List()”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t List ” + tablename.ToLower() + “List = new List();”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spGet” + tablename + “List\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
sb.Append(Environment.NewLine + “\t\t\t\t using (SqlDataReader rd = cmd.ExecuteReader())”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t while (rd.Read())”);
sb.Append(Environment.NewLine + “\t\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t ” + tablename.ToLower() + “List.Add(Load” + tablename + “Entity(rd));”);
sb.Append(Environment.NewLine + “\t\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “List;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public List Search” + tablename + “List(string ” + tablename.ToLower() + “Name)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t List ” + tablename.ToLower() + “List = new List();”);
sb.Append(Environment.NewLine + “\t\t\t using (SqlCommand cmd = sqlConn.CreateCommand())”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandText = ” + “\”spSearch” + tablename + “List\”;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.CommandType = CommandType.StoredProcedure;”);
sb.Append(Environment.NewLine + “\t\t\t\t cmd.Parameters.AddWithValue(” + “\”@” + tablename + “Name\”, ” + tablename.ToLower() + “Name);”);
sb.Append(Environment.NewLine + “\t\t\t\t using (SqlDataReader rd = cmd.ExecuteReader())”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t while (rd.Read())”);
sb.Append(Environment.NewLine + “\t\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t\t ” + tablename.ToLower() + “List.Add(Load” + tablename + “Entity(rd));”);
sb.Append(Environment.NewLine + “\t\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “List;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “\t }”);
sb.Append(Environment.NewLine + “}”);
sb.Append(Environment.NewLine + “”);
}
else if (data == name)
{
sb.Append(“using System;”);
sb.Append(Environment.NewLine + “using System.Collections.Generic;”);
sb.Append(Environment.NewLine + “using System.Text;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “namespace ” + data);
sb.Append(Environment.NewLine + “{“);
filename = tablename + “Entity”;
sb.Append(Environment.NewLine + “\t public class ” + tablename + “Entity”);
sb.Append(Environment.NewLine + “\t {“);
foreach (DataRow rw in ds.Tables[0].Rows)
{
var = Convert.ToString(rw[0]).Substring(0, 1).ToLower() + Convert.ToString(rw[0]).Substring(1, Convert.ToString(rw[0]).Length – 1);
if (Convert.ToString(rw[1]) == “int”)
sb.Append(Environment.NewLine + “\t\t private ” + Convert.ToString(rw[1]) + ” _” + var + “;”);
else
sb.Append(Environment.NewLine + “\t\t private string _” + Convert.ToString(rw[0]) + “;”);
}
foreach (string forKey in foreignList)
sb.Append(Environment.NewLine + “\t\t private ” + forKey + “Entity ” + forKey.ToLower() + “;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public ” + tablename + “Entity()”);
sb.Append(Environment.NewLine + “\t\t {“);
foreach (string forKey in foreignList)
sb.Append(Environment.NewLine + “\t\t\t ” + forKey.ToLower() + ” = new ” + forKey + “Entity();”);
sb.Append(Environment.NewLine + “\t\t }”);
foreach (DataRow row in ds.Tables[0].Rows)
{
var = Convert.ToString(row[0]).Substring(0, 1).ToLower() + Convert.ToString(row[0]).Substring(1, Convert.ToString(row[0]).Length – 1);
sb.Append(Environment.NewLine + “”);
if (Convert.ToString(row[1]) == “int”)
sb.Append(Environment.NewLine + “\t\t public int ” + Convert.ToString(row[0]));
else
sb.Append(Environment.NewLine + “\t\t public string ” + Convert.ToString(row[0]));
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t get”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t return _” + var + “;”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t set”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t if (_” + var + ” != value)”);
sb.Append(Environment.NewLine + “\t\t\t\t\t _” + var + “= value;”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t }”);
}
foreach (string f in foreignList)
{
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public string ” + f + “Name”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t get”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t return ” + f.ToLower() + “.” + f + “Name;”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t set”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t if (” + f.ToLower() + “.” + f + “Name != value)”);
sb.Append(Environment.NewLine + “\t\t\t\t\t ” + f.ToLower() + “.” + f + “Name = value;”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t }”);
}
sb.Append(Environment.NewLine + “\t }”);
sb.Append(Environment.NewLine + “}”);
sb.Append(Environment.NewLine + “”);
}
else if (business == name)
{
sb.Append(“using System;”);
sb.Append(Environment.NewLine + “using System.Collections.Generic;”);
sb.Append(Environment.NewLine + “using System.Text;”);
sb.Append(Environment.NewLine + “using ” + dal + “;”);
sb.Append(Environment.NewLine + “using ” + data + “;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “namespace ” + business);
sb.Append(Environment.NewLine + “{“);
filename = “cls” + tablename + “BAL”;
sb.Append(Environment.NewLine + “\t public class ” + filename);
sb.Append(Environment.NewLine + “\t {“);
sb.Append(Environment.NewLine + “\t\t cls” + tablename + “DAL ” + tablename.ToLower() + “DAL;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public cls” + tablename + “BAL()”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t cityDAL = new cls” + tablename + “DAL();”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Insert(” + tablename + “Entity ” + tablename.ToLower() + “)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Insert” + tablename + “(” + tablename.ToLower() + “);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Update(” + tablename + “Entity ” + tablename.ToLower() + “)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Update” + tablename + “(” + tablename.ToLower() + “);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public int Delete(int ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Delete” + tablename + “(” + tablename.ToLower() + “Id);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public List GetAll” + tablename.Substring(0, tablename.Length – 1) + “ies()”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Retrieve” + tablename + “List();”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public ” + tablename + “Entity Get” + tablename + “ById(int ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Retrieve” + tablename + “ById(” + tablename.ToLower() + “Id);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public ” + tablename + “Entity Get” + tablename + “ByName(string ” + tablename.ToLower() + “Name)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Retrieve” + tablename + “ByName(” + tablename.ToLower() + “Name);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public List Search” + tablename + “(string ” + tablename.ToLower() + “Name)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t return ” + tablename.ToLower() + “DAL.Search” + tablename + “List(” + tablename + “Name);”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public bool CheckForNewDuplicate” + tablename + “Name(string ” + tablename.ToLower() + “)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t bool duplicate = false;”);
sb.Append(Environment.NewLine + “\t\t\t List ” + tablename.ToLower() + “List = new List();”);
sb.Append(Environment.NewLine + “\t\t\t ” + tablename.ToLower() + “List = ” + tablename.ToLower() + “DAL.Retrieve” + tablename + “List();”);
sb.Append(Environment.NewLine + “\t\t\t foreach (” + tablename + “Entity c in ” + tablename.ToLower() + “List)”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t if (c.” + tablename + “Name.ToUpper() == ” + tablename.ToLower() + “.ToUpper())”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t duplicate = true;”);
sb.Append(Environment.NewLine + “\t\t\t\t\t break;”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return duplicate;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “\t\t public bool CheckForExistingDuplicate” + tablename + “Name(string ” + tablename.ToLower() + “, int ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t bool duplicate = false;”);
sb.Append(Environment.NewLine + “\t\t\t List ” + tablename.ToLower() + “List = new List();”);
sb.Append(Environment.NewLine + “\t\t\t ” + tablename.ToLower() + “List = ” + tablename.ToLower() + “DAL.Retrieve” + tablename + “List();”);
sb.Append(Environment.NewLine + “\t\t\t foreach (” + tablename + “Entity c in ” + tablename.ToLower() + “List)”);
sb.Append(Environment.NewLine + “\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t if (c.” + tablename + “Name.ToUpper() == ” + tablename.ToLower() + “.ToUpper() & c.” + tablename + “Id != ” + tablename.ToLower() + “Id)”);
sb.Append(Environment.NewLine + “\t\t\t\t {“);
sb.Append(Environment.NewLine + “\t\t\t\t\t duplicate = true;”);
sb.Append(Environment.NewLine + “\t\t\t\t\t break;”);
sb.Append(Environment.NewLine + “\t\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t }”);
sb.Append(Environment.NewLine + “\t\t\t return duplicate;”);
sb.Append(Environment.NewLine + “\t\t }”);
sb.Append(Environment.NewLine + “\t }”);
sb.Append(Environment.NewLine + “}”);
sb.Append(Environment.NewLine + “”);
}
else if (name == “Interface”)
{
sb.Append(“using System;”);
sb.Append(Environment.NewLine + “using System.Collections.Generic;”);
sb.Append(Environment.NewLine + “using System.Text;”);
sb.Append(Environment.NewLine + “using TestDataEntity;”);
sb.Append(Environment.NewLine + “using System.Configuration;”);
sb.Append(Environment.NewLine + “”);
sb.Append(Environment.NewLine + “namespace ” + business);
sb.Append(Environment.NewLine + “{“);
filename = “I” + tablename;
sb.Append(Environment.NewLine + “\t public interface ” + filename);
sb.Append(Environment.NewLine + “\t {“);
sb.Append(Environment.NewLine + “\t\t int InsertCity(CityEntity city);”);
sb.Append(Environment.NewLine + “\t\t int UpdateCity(CityEntity city);”);
sb.Append(Environment.NewLine + “\t\t int DeleteCity(int cityId);”);
sb.Append(Environment.NewLine + “\t\t List RetrieveCityList();”);
sb.Append(Environment.NewLine + “\t\t CityEntity RetrieveCityById(int cityId);”);
sb.Append(Environment.NewLine + “\t\t CityEntity RetrieveCityByName(string cityName);”);
sb.Append(Environment.NewLine + “\t\t List SearchCityList(string cityName);”);
sb.Append(Environment.NewLine + “\t }”);
sb.Append(Environment.NewLine + “}”);
sb.Append(Environment.NewLine + “”);
}
this.txtGeneratedCode.Text = sb.ToString();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void btnGenerate_Click(object sender, EventArgs e)
{
try
{
if (className != string.Empty)
GenerateCode(className);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void btnReset_Click(object sender, EventArgs e)
{
ResetEntry();
}

private void cboTables_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (this.cboTables.SelectedItem != null)
table = this.cboTables.SelectedItem.ToString();
PopulateGrid();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void btnGenerateFile_Click(object sender, EventArgs e)
{
try
{
if (className != string.Empty)
GenerateCode(className);
string path = @”C:\GeneratedCode\” + filename + “.cs”;
if (!File.Exists(path))
File.WriteAllText(path, sb.ToString());
else
MessageBox.Show(“File already exists !!!”);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}

private void cboNamespace_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (this.cboNamespace.SelectedItem != null)
className = this.cboNamespace.SelectedItem.ToString();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
}

Posted in ASP.NET 3.5, ASP.NET 3.5 And C# 3.5, C# 3.5, C# 3.5 and ADO.NET Entity Framework 3.5 | Leave a comment

How to insert audio file into SQL Server and retrieve it back and play it?

This is how the form looks like.

This is the source code,
This is the code for inserting audio file into sql server,
SqlConnection con = new SqlConnection(“Data Source=DEV-ARNOLD;Initial Catalog=Sample;User ID=sa;Password=passw0rd”);
SqlCommand com = new SqlCommand(“insert into tblVoice(FileName, FilePath, fldvoice) values(@Filename,@FilePath,@voice)”, con);
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();

byte[] stream = File.ReadAllBytes(fileDialog.FileName);
if (stream.Length > 0)
{
com.Parameters.AddWithValue(“@Filename”, fileDialog.SafeFileName);
com.Parameters.AddWithValue(“@FilePath”, fileDialog.FileName);
com.Parameters.AddWithValue(“@voice”, stream);
con.Open();
int result = com.ExecuteNonQuery();
if (result > 0)
MessageBox.Show(“insert done”);
con.Close();
}
This is the code for retrieving the audio file from sql server,
SqlConnection con = new SqlConnection(“Data Source=DEV-ARNOLD;Initial Catalog=Sample;User ID=sa;Password=passw0rd”);
SqlCommand com = new SqlCommand(“select * from tblVoice”, con);
con.Open();
DataTable dt = new DataTable();
SqlDataReader dr = com.ExecuteReader();
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
dt.Load(dr);
dr.Close();
con.Close();
byte[] stream = null;
string path = @”C:\SynRISTempFiles\”;
string name = string.Empty;
foreach (DataRow rw in dt.Rows)
{
if (Convert.ToString(rw[0]) == fileDialog.SafeFileName)
{
stream = (byte[])rw[2];
name = (string)rw[0];
}
}
File.WriteAllBytes(path + name, stream);
axWindowsMediaPlayer1.URL = path + name;

References that I used:

http://www.codeproject.com/KB/database/AudioInSQLServer.aspx

http://coder000.com/store-retrieve-binary-data-blobs-audio-video-image-exe-etc-in-database-in-vb-net/

http://www.codeproject.com/KB/audio-video/Concatenation_Wave_Files.aspx

Posted in C# 3.5 | Leave a comment

How to determine which form is open?

You wish to determine which form is open. Here is the code that will determine whether the form is open or not.
PDFViewer viewer = null;
foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.GetType() == typeof(PDFViewer))
{
viewer = (PDFViewer)OpenForm;
}
}
viewer.CloseForm();

Posted in C# 3.5 | Leave a comment

Silverlight 4 Book Details and Links

If you are looking for books in silverlight 4 that is posted on this site,
source of recommended books
except for Microsoft Silverlight 4 Step By Step By Laurence Moroney

Microsoft Silverlight 4 Step By Step By Laurence Moroney

Silverlight 4 in Action By Pete Brown

Silverlight 4 Unleashed by Laurent Bugnion
or this one

Professional Silverlight 4 by Jason Beres, Bill Evjen, Devin Rader

Microsoft Silverlight 4 and Sharepoint 2010 Integration by Gaston C Hillar

Silverlight 4 Jumpstart by David Yack

You may view these books online thru this site,

Online Reading (not for Free)

Personally I have not yet read any of these books or ebook.

Posted in Silverlight 4 | Leave a comment

How to create Silverlight Business Application using Silverlight 3 Ria Services?

Creating Silverlight Business Application using Silverlight 3 Ria Services

Tools that I have used in this tutorial project:

SQL Server 2005 Standard Edition

Visual Studio 2008 Professional/Team System Edition with its SP1

Silverlight 3

Silverlight 3 SDK

Microsoft Expression Blend 3

Microsoft Expression Blend 3 SDK

Microsoft Silverlight 3 Tools for Visual Studio 2008 SP1 – ENU

WCF RIA Services Beta

WCF RIA Services Toolkit (April 2011)

WCF RIA Services v1.0 SP1

This is my main page,
S3RSMainPage

This is my city listing page,
S3RSCityListingPage

This is my city listing xaml,

<navigation:Page xmlns:riaControls=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Ria”  xmlns:data1=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”  x:Class=”MySilverlight3BusinessApplication.Views.CityListing”

           xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

           xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

           xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;

           xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;

           mc:Ignorable=”d”

           xmlns:navigation=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation”

           xmlns:data= “clrnamespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”

           xmlns:rc=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Ria”

           xmlns:ds=”clr-namespace:MySilverlight3BusinessApplication.Web.Services”

           d:DesignWidth=”640″ d:DesignHeight=”480″

           Title=”City”>

    <Grid x:Name=”LayoutRoot”>

        <Grid.Background>

            <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>

                <GradientStop Color=”#FF072A39″ Offset=”1″/>

                <GradientStop Color=”#FF0878AB”/>

            </LinearGradientBrush>

        </Grid.Background>

        <Grid.RowDefinitions>

            <RowDefinition Height=”0.112*”/>

            <RowDefinition Height=”0.888*”/>

        </Grid.RowDefinitions>

        <riaControls:DomainDataSource x:Name=”CityDataSource” QueryName=”GetTblCityQuery” AutoLoad=”True”>

            <riaControls:DomainDataSource.DomainContext>

                <ds:TestDbDomainContext></ds:TestDbDomainContext>

            </riaControls:DomainDataSource.DomainContext>

        </riaControls:DomainDataSource>

        <TextBlock Style=”{StaticResource HeaderTextStyle}” HorizontalAlignment=”Left” Margin=”8,8,0,19″ Width=”212″ Text=”City List” TextWrapping=”Wrap”/>

        <data1:DataGrid x:Name=”CityGrid” Grid.Row=”1″ Background=”White” ItemsSource=”{Binding ElementName=CityDataSource, Path=Data}”></data1:DataGrid>

        <!–<data1:DataGrid x:Name=”CityGrid” Grid.Row=”1″ Loaded=”CityGrid_Loaded”></data1:DataGrid>–>

    </Grid>

</navigation:Page>

Here is my code in C# of course,

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Navigation;

using System.Windows.Controls.Data;

using MySilverlight3BusinessApplication.Web.Services;

namespace MySilverlight3BusinessApplication.Views

{

    public partial class CityListing : Page

    {

        public CityListing()

        {

            InitializeComponent();

        }

        // Executes when the user navigates to this page.

        protected override void OnNavigatedTo(NavigationEventArgs e)

        {

        }

        //private void CityGrid_Loaded(object sender, RoutedEventArgs e)

        //{

        //    TestDbDomainContext context = new TestDbDomainContext();

        //    CityGrid.ItemsSource = context.tblCities;

        //    context.Load(context.GetTblCityQuery());

        //}

    }

}

You notice that there are commented out portion on both xaml and my code. I base and follow the steps in this tutorial. Here is my reference link below,

http://dotnetslackers.com/articles/silverlight/RIA-Services-With-Silverlight-3-Part1.aspx

http://dotnetslackers.com/articles/silverlight/RIA-Services-With-Silverlight-3-Part2.aspx

Posted in ASP.NET 3.5 And Silverlight 3, Silverlight 3, WCF RIA Services | Leave a comment

Expression Blend 5 day Training

This 5 day training is only available online, these videos cannot be downloaded, it can only be viewed online. Please see below link …

http://www.microsoft.com/expression/resources/blendtraining/

Table of Contents

Day 1
Lesson 1 – An Introduction to Silverlight and Expression Blend Part 1
Lesson 2 – Learn How to keep Precise control over your application UI using dynamic layout
Lesson 3 – Use your existing Photoshop and Illustrator Skills with Silverlight and Expression Blend

Day 2
Lesson 1 – Learn how to use Sketchflow to rapidly prototype, present and receive feedback on your idea
Lesson 2 – Dive deeper into the platform and tools: An Introduction to Silverlight and Blend Part 2
Lesson 3 – Transferring your Skills from Flash to Silverlight Part 1
Lesson 4 – Transferring your Skills from Flash to Silverlight Part 2
Lesson 5 – Using drawing and graphics tools in Expression Blend

Day 3
Lesson 1 – Tips and Tricks (Things you should Know)
Lesson 2 – Creating and modifying User Interface controls
Lesson 3 – Using animation and interactivity to bring your application to life
Lesson 4 – Project 1:Let’s use the skills you’ve learnt in a real project

Day 4
Lesson 1 – Working with Data when designing your UI
Lesson 2 – Creating Editing and Incorporating Video into Silverlight project with Expression Encoder
Lesson 3 – HTML Integration and Publishing
Lesson 4 – Project 2: Create a WordPress Site using HTML, the Microsoft Web Platform and the Skills you’re now familiar with in Expression Blend and SketchFlow
Lesson 5 – Top gotcha’s when working with Silverlight and Expression Blend

Day 5
Lesson 1 – Explore new and improved features in Expression Blend 4

Posted in Expression Blend 4 | Leave a comment

Microsoft SQL Server Service Pack 3

I copied the details of SQL Server 2005 SP3 from the link below, It describe the system requirements, steps, which edition of sql server that applies with this version of service pack.

Overview

——————————————————————————–

Service Pack 3 for Microsoft SQL Server 2005 is now available. SQL Server 2005 service packs are cumulative, and this service pack upgrades all service levels of SQL Server 2005 to SP3. You can use these packages to upgrade any of the following SQL Server 2005 editions:

•Enterprise
•Enterprise Evaluation
•Developer
•Standard
•Workgroup

Note: To upgrade SQL Server 2005 Express Edition, obtain the SP3 version of Express Edition or Express Edition with Advanced Services.

For a list of new features and improvements that are included in SQL Server 2005 SP3, review the What’s New document.
Top of pageSystem Requirements

——————————————————————————–
•Supported Operating Systems:Windows 2000 Service Pack 4;Windows 7;Windows Server 2003;Windows Server 2008;Windows Server 2008 R2;Windows Vista;Windows XP
•32-bit systems (x86)
◦PC with Intel or compatible Pentium III 600 MHz or higher processor (1 GHz or faster recommended)
•64-bit systems (x64, ia64)
◦1GHz or faster processor
•Minimum of 512 MB of RAM (1 GB or more recommended)
•675 MB of available hard disk space

Note: SQL Server 2005 Service Pack 3 (SP3) is designed to run on Windows Vista and Windows Server 2008. For more information about installing and running SQL Server 2005 on Windows Vista and Windows Server 2008, see this Microsoft Web site.
Top of pageInstructions

——————————————————————————–

Note: You must have administrative rights on the computer to install SQL Server 2005 SP3.
Step 1: Download and review the setup documentation and readme file. For known issues, review the release notes.

Step 2: Download the appropriate package by clicking one of the links below. To start the installation immediately, click Run. To install SP3 at a later time, click Save.

Here is the link
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ae7387c3-348c-4faa-8ae5-949fdfbe59c4

Posted in MS SQL Server 2005 | Leave a comment

Silverlight 4 Resources

Silverlight 4 Tools, Samples, Documents, Hands-On Labs, Books, Whitepapers
http://www.silverlight.net/getstarted/

Microsoft Expression Blend Software Development Kit (SDK) for Silverlight 4
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=D197F51A-DE07-4EDF-9CBA-1F1B4A22110D&displaylang=en

Silverlight 4 Toolkit
http://silverlight.codeplex.com/releases/view/43528

Silverlight 4 Samples
http://silverlight.net/content/samples/sl4/toolkitcontrolsamples/run/default.html

Silverlight for Windows Phone Toolkit – Feb 2011
http://silverlight.codeplex.com/releases/view/60291

Deeveloper Tools For Windows Phone and XBOX 360
http://create.msdn.com/en-us/home/getting_started
http://create.msdn.com/en-US/

Microsoft Expression Blend 4 + SketchFlow
http://expression.microsoft.com/en-us/cc136530.aspx

Download Trial Version Of Microsoft Expression
http://www.microsoft.com/expression/try-it/Default.aspx#PageTop

WCF RIA Services
http://www.silverlight.net/getstarted/riaservices/
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6f834bf7-ffde-4d5d-8573-18541762118b&displaylang=en

Posted in ASP.NET 4 and C# 4 and Silverlight 4, ASP.NET 4 and Silverlight 4, Silverlight 4, Silverlight 4 and Expression Studio 4 | Leave a comment

How to disable back button of browser and not delete the history?

To disable back button of browser … delete history
Put this javascript at the <head> tag
    <script type=”text/javascript”>
        function setFocus()
        {
            document.getElementById(“contentPage”).focus();
            var URL;
            var i;
            var QryStrValue;
            URL = window.location.href;
            i = URL.indexOf(“?”);
            QryStrValue = URL.substring(i + 1);
            if (QryStrValue != ‘X’)
            {
                window.location = URL + “?X”;
            }
        }
     </Script>

Then call your function using onload event in <body> tag.
<body onload=”setFocus()”>

Here is the reference that I use:
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/60682

Posted in ASP.NET 3.5 And JavaScript, HTML And JavaScript, JavaScript | Leave a comment

Set focus on your content page upon loading

If you wnat to set focus on the content page, put your javascript on <head> tag, then call the function using onload event on the body. Then create an id on the part that you wish to set focus.

<head runat=”server”>
    <title></title>
    <asp:ContentPlaceHolder ID=”head” runat=”server”>
    </asp:ContentPlaceHolder>
    <link href=”Template.css” rel=”stylesheet” type=”text/css” />
    <link href=”Main_Menu.css” rel=”stylesheet” type=”text/css” />
    <link type=”text/css” href=”css/ui-lightness/jquery-ui-1.8.12.custom.css” rel=”stylesheet” />
    <style type=”text/css”>

</head>

….

<body onload=”setFocus()”>
    <form id=”form1″ runat=”server”>

<table border=”0″ cellpadding=”0″ cellspacing=”0″ width=”100%”>
          <tr>
                    <td valign=”top” id=”contentPage”>

….

Javascript focus method
http://www.bloggingdeveloper.com/post/Setting-Focus-Using-Javascript-to-an-Input-Field-(Textbox)-when-the-Page-Loads.aspx
http://forums.htmlhelp.com/index.php?showtopic=5399
http://www.roseindia.net/javascript/javascript-focus-method.shtml

Posted in ASP.NET 3.5 And JavaScript, ASP.NEt And C# 3.5 And Javascript, JavaScript | Leave a comment

Silverlight3 SDK and developer runtime download links

Microsoft® Silverlight™ 3 Tools for Visual Studio 2008 SP1
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9442b0f2-7465-417a-88f3-5e7b5409e9dd

http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=9442b0f2-7465-417a-88f3-5e7b5409e9dd

Microsoft Silverlight 3 developer runtime

http://silverlight.dlservice.microsoft.com/download/0/D/E/0DEAFE9C-8451-4497-8F8B-DFF82B729818/Silverlight_Developer.exe

Posted in ASp.NET 3.5 And C# 3.5 And Silverlight 3, ASP.NET 3.5 And Silverlight 3, Silverlight 3 | Leave a comment

ReadyBoost For Windows 7

ReadyBoost feature is readily available for Windows Vista and Windows 7. It will speed up your system especially when your HDD is lower than 7200 rpm.

Just click one of the link on how to use readyboost to speed up your system.

http://windows.microsoft.com/en-US/windows7/products/features/readyboost
http://windows.microsoft.com/en-US/windows7/Using-memory-in-your-storage-device-to-speed-up-your-computer
http://windows.microsoft.com/en-US/windows7/Turn-ReadyBoost-on-or-off-for-a-storage-device
http://windows.microsoft.com/en-US/windows7/Ways-to-improve-your-computers-performance
http://technet.microsoft.com/en-us/magazine/ff356869.aspx
http://en.wikipedia.org/wiki/ReadyBoost
http://windows7.iyogi.com/performance/readyboost-a-way-to-speed-up-windows-7/
http://www.thetechyblog.com/using-readyboost-in-windows-7/

Posted in Windows 7 | Leave a comment

How to create CRUD using Linq to Entity in ASP.NET 4?

In this project, I use Microsoft Visual C# 2010 Express Edition and Microsoft Visual Web Developer 2010 Express Edition

You need to create a class library project first. Then create a ADO.NET Entity Framework, then create a class and interface for each table or object.

Step 1 – Find and Click Start Then Find and Click Microsoft Visual C# 2010 Express

Step 2 – Find and Click New Project under File.

Step 3 – Find and Select Class Library then enter your chosen name for this class library project.

Step 4 – Click on Add new data Source under data.

Step 5 – Right Click and select Add Then new item.

Step 6 – Select ADO.NET Entity Data Model then type in your chosen name for your entity model.

Step 7 – Choose “Generate from Database” then click next.

Step 8 – Click on “New Connection …” to create new connection. Then type in your chosen name for your connection string. Then click on next.

Step 9 – Choose your objects Then type in your chosen name for your model namespace.

Step 10 – All your chosen objects will be generated automatically.

To create a class for each tables, here are the steps:

Steps 1 – Right Click and select Add Then New Item. You need to add class.

Step 2 – Choose Class template, then type in your chosen class name.

Step 3 – To create interface, just repeat the steps in creating a class.

Here are the samples codes for both interface and class file:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace MyLinqToEntityClassLibrary

{

    interface PersonInterface

    {

        List<tblPerson> RetrievePersonList();

        List<tblPerson> RetrievePersonListByName(string name, string sortExpression, string sortDirection);

        tblPerson RetrievePersonByID(int id);

        tblPerson RetrievePersonByName(string name);

        int CreatePerson(tblPerson person);

        int UpdatePerson(tblPerson person);

        int DeletePerson(int id);

    }

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Configuration;

namespace MyLinqToEntityClassLibrary

{

    public class PersonClassificationCompanyCityCountryPosition

    {

        tblPerson person;

        tblClassification classification;

        tblCompany company;

        tblCity city;

        tblCountry country;

        tblPosition position;

        string personName = string.Empty;

        public PersonClassificationCompanyCityCountryPosition()

        {

            person = new tblPerson();

            classification = new tblClassification();

            company = new tblCompany();

            city = new tblCity();

            country = new tblCountry();

            position = new tblPosition();

        }

        public DateTime PersonBirthDate

        {

            get { return person.PersonBirthDate; }

            set

            {

                if (person.PersonBirthDate != value)

                    person.PersonBirthDate = value;

            }

        }

        public int ClassificationId

        {

            get { return person.PersonClassificationId; }

            set

            {

                if (person.PersonClassificationId != value)

                    person.PersonClassificationId = value;

            }

        }

        public string ClassificationName

        {

            get { return classification.ClassificationName; }

            set

            {

                if (classification.ClassificationName != value)

                    classification.ClassificationName = value;

            }

        }

        public int? CompanyId

        {

            get { return person.PersonCompanyId; }

            set

            {

                if (person.PersonCompanyId != value)

                    person.PersonCompanyId = value;

            }

        }

        public string CompanyName

        {

            get { return company.CompanyName; }

            set

            {

                if (company.CompanyName != value)

                    company.CompanyName = value;

            }

        }

        public string PersonFirstName

        {

            get { return person.PersonFirstName; }

            set

            {

                if (person.PersonFirstName != value)

                    person.PersonFirstName = value;

            }

        }

        public string PersonGender

        {

            get { return person.PersonGender; }

            set

            {

                if (person.PersonGender != value)

                    person.PersonGender = value;

            }

        }

        public string PersonHomeAddress

        {

            get { return person.PersonHomeAddress; }

            set

            {

                if (person.PersonHomeAddress != value)

                    person.PersonHomeAddress = value;

            }

        }

        public string PersonHomeCellularPhone

        {

            get { return person.PersonHomeCellularPhone; }

            set

            {

                if (person.PersonHomeCellularPhone != value)

                    person.PersonHomeCellularPhone = value;

            }

        }

        public int CityId

        {

            get { return person.PersonHomeCityId; }

            set

            {

                if (person.PersonHomeCityId != value)

                    person.PersonHomeCityId = value;

            }

        }

        public string CityName

        {

            get { return city.CityName; }

            set

            {

                if (city.CityName != value)

                    city.CityName = value;

            }

        }

        public int CountryId

        {

            get { return person.PersonHomeCountryId; }

            set

            {

                if (person.PersonHomeCountryId != value)

                    person.PersonHomeCountryId = value;

            }

        }

        public string CountryName

        {

            get { return country.CountryName; }

            set

            {

                if (country.CountryName != value)

                    country.CountryName = value;

            }

        }

        public string PersonHomeEmail

        {

            get { return person.PersonHomeEmail; }

            set

            {

                if (person.PersonHomeEmail != value)

                    person.PersonHomeEmail = value;

            }

        }

        public string PersonHomePhone

        {

            get { return person.PersonHomePhone; }

            set

            {

                if (person.PersonHomePhone != value)

                    person.PersonHomePhone = value;

            }

        }

        public int PersonID

        {

            get { return person.PersonId; }

            set

            {

                if (person.PersonId != value)

                    person.PersonId = value;

            }

        }

        public string PersonLastName

        {

            get { return person.PersonLastName; }

            set

            {

                if (person.PersonLastName != value)

                    person.PersonLastName = value;

            }

        }

        public string PersonMiddleName

        {

            get { return person.PersonMiddleName; }

            set

            {

                if (person.PersonMiddleName != value)

                    person.PersonMiddleName = value;

            }

        }

        public int? PositionId

        {

            get { return person.PersonPositionId; }

            set

            {

                if (person.PersonPositionId != value)

                    person.PersonPositionId = value;

            }

        }

        public string PositionName

        {

            get { return position.PositionName; }

            set

            {

                if (position.PositionName != value)

                    position.PositionName = value;

            }

        }

        public string PersonName

        {

            get

            {

                if (personName == null | personName == string.Empty)

                    personName = person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName;

                return personName;

            }

            set

            {

                if (personName != value)

                    personName = value;

                if (personName == null | personName == string.Empty)

                    personName = person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName;

            }

        }

    }

    public class PersonClassificationCompanyCityCountryPositionBLL

    {

        PersonClassificationCompanyCityCountryPosition personClassificationCompanyCityCountryPosition;

        List<PersonClassificationCompanyCityCountryPosition> personClassificationCompanyCityCountryPositionList;

        TestDBEntitiesConnectionString dbEntity;

        string connString = ConfigurationManager.ConnectionStrings["TestDBEntitiesConnectionString"].ConnectionString;

        IOrderedQueryable personQuery;

        public PersonClassificationCompanyCityCountryPositionBLL()

        {

            personClassificationCompanyCityCountryPosition = new PersonClassificationCompanyCityCountryPosition();

            personClassificationCompanyCityCountryPositionList = new List<PersonClassificationCompanyCityCountryPosition>();

            dbEntity = new TestDBEntitiesConnectionString(connString);

        }

        public List<PersonClassificationCompanyCityCountryPosition> RetrievePersonNameListByName(string name, string sortExpression, string sortDirection)

        {

            List<PersonClassificationCompanyCityCountryPosition> list = new List<PersonClassificationCompanyCityCountryPosition>();

            List<tblPerson> personList = new List<tblPerson>();

            List<tblCity> cityList = new List<tblCity>();

            List<tblClassification> classificationList = new List<tblClassification>();

            List<tblCompany> companyList = new List<tblCompany>();

            List<tblCountry> countryList = new List<tblCountry>();

            List<tblPosition> positionList = new List<tblPosition>();

            PersonClass personBll = new PersonClass();

            CityClass cityBll = new CityClass();

            CountryClass countryBll = new CountryClass();

            CompanyClass companyBll = new CompanyClass();

            PositionClass positionBll = new PositionClass();

            ClassificationClass classificationBll = new ClassificationClass();

            cityList = cityBll.RetrieveCityList();

            countryList = countryBll.RetrieveCountryList();

            companyList = companyBll.RetrieveCompanyList();

            classificationList = classificationBll.RetrieveClassificationList();

            positionList = positionBll.RetrievePositionList();

            personList = (from p in dbEntity.tblPersons

                          where (p.PersonFirstName + ” ” + p.PersonMiddleName + ” ” + p.PersonLastName).Contains(name)

                          select p).ToList<tblPerson>();

            foreach (tblPerson person in personList)

            {

                personClassificationCompanyCityCountryPosition = new PersonClassificationCompanyCityCountryPosition();

                personClassificationCompanyCityCountryPosition.CityId = person.PersonHomeCityId;

                foreach (tblCity city in cityList)

                {

                    if (city.CityId == person.PersonHomeCityId)

                    {

                        personClassificationCompanyCityCountryPosition.CityName = city.CityName;

                        break;

                    }

                }

                personClassificationCompanyCityCountryPosition.ClassificationId = person.PersonClassificationId;

                foreach (tblClassification classification in classificationList)

                {

                    if (classification.ClassificationId == person.PersonClassificationId)

                    {

                        personClassificationCompanyCityCountryPosition.ClassificationName = classification.ClassificationName;

                        break;

                    }

                }

                personClassificationCompanyCityCountryPosition.CompanyId = person.PersonCompanyId;

                foreach (tblCompany company in companyList)

                {

                    if (company.CompanyId == person.PersonCompanyId)

                    {

                        personClassificationCompanyCityCountryPosition.CompanyName = company.CompanyName;

                        break;

                    }

                }

                personClassificationCompanyCityCountryPosition.CountryId = person.PersonHomeCountryId;

                foreach (tblCountry country in countryList)

                {

                    if (country.CountryId == person.PersonHomeCountryId)

                    {

                        personClassificationCompanyCityCountryPosition.CountryName = country.CountryName;

                        break;

                    }

                }

                personClassificationCompanyCityCountryPosition.PersonBirthDate = person.PersonBirthDate;

                personClassificationCompanyCityCountryPosition.PersonFirstName = person.PersonFirstName;

                personClassificationCompanyCityCountryPosition.PersonGender = person.PersonGender;

                personClassificationCompanyCityCountryPosition.PersonHomeAddress = person.PersonHomeAddress;

                personClassificationCompanyCityCountryPosition.PersonHomeCellularPhone = person.PersonHomeCellularPhone;

                personClassificationCompanyCityCountryPosition.PersonHomeEmail = person.PersonHomeEmail;

                personClassificationCompanyCityCountryPosition.PersonHomePhone = person.PersonHomePhone;

                personClassificationCompanyCityCountryPosition.PersonID = person.PersonId;

                personClassificationCompanyCityCountryPosition.PersonLastName = person.PersonLastName;

                personClassificationCompanyCityCountryPosition.PersonMiddleName = person.PersonMiddleName;

                personClassificationCompanyCityCountryPosition.PersonName = person.PersonFirstName + ” ” +  person.PersonMiddleName + ” ” + person.PersonLastName;

                personClassificationCompanyCityCountryPosition.PositionId = person.PersonPositionId;

                foreach (tblPosition position in positionList)

                {

                    if (position.PositionId == person.PersonPositionId)

                    {

                        personClassificationCompanyCityCountryPosition.PositionName = position.PositionName;

                        break;

                    }

                }

                if (!list.Exists(pccccp => pccccp.PersonID == personClassificationCompanyCityCountryPosition.PersonID))

                    list.Add(personClassificationCompanyCityCountryPosition);

            }

            if (sortDirection == “ascending”)

            {

                switch (sortExpression)

                {

                    case “CityName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.CityName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “ClassificationName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.ClassificationName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “CompanyName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.CompanyName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “CountryName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.CountryName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonBirthDate”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonBirthDate).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonFirstName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonFirstName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonGender”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonGender).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeAddress”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonHomeAddress).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeCellularPhone”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonHomeCellularPhone).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeEmail”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonHomeEmail).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomePhone”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonHomePhone).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonLastName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonLastName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonMiddleName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonMiddleName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PersonName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PositionName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderBy(p => p.PositionName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                }

            }

            else

            {

                switch (sortExpression)

                {

                    case “CityName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.CityName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “ClassificationName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.ClassificationName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “CompanyName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.CompanyName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “CountryName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.CountryName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonBirthDate”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonBirthDate).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonFirstName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonFirstName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonGender”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonGender).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeAddress”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonHomeAddress).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeCellularPhone”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonHomeCellularPhone).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomeEmail”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonHomeEmail).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonHomePhone”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonHomePhone).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonLastName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonLastName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonMiddleName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonMiddleName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PersonName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PersonName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                    case “PositionName”:

                        personClassificationCompanyCityCountryPositionList = list.OrderByDescending(p => p.PositionName).ToList<PersonClassificationCompanyCityCountryPosition>();

                        break;

                }

            }

            return personClassificationCompanyCityCountryPositionList;

        }

        public IOrderedQueryable RetrievePersonQueryListByName(string name , string sortExpression, string sortDirection)

        {

            var data = (from p in dbEntity.tblPersons

                        join cl in dbEntity.tblClassifications

                        on p.PersonClassificationId equals cl.ClassificationId

                        join com in dbEntity.tblCompanies

                        on p.PersonCompanyId equals com.CompanyId

                        join c in dbEntity.tblCities

                        on p.PersonHomeCityId equals c.CityId

                        join co in dbEntity.tblCountries

                        on p.PersonHomeCountryId equals co.CountryId

                        join po in dbEntity.tblPositions

                        on p.PersonPositionId equals po.PositionId

                        where (p.PersonFirstName + ” ” + p.PersonMiddleName  + ” ” + p.PersonLastName).Contains(name)

                        orderby sortExpression + ” ” + sortDirection

                        select new

                        {

                            p.PersonBirthDate,

                            p.PersonClassificationId,

                            cl.ClassificationName,

                            p.PersonCompanyId,

                            com.CompanyName,

                            p.PersonFirstName,

                            p.PersonGender,

                            p.PersonHomeAddress,

                            p.PersonHomeCellularPhone,

                            p.PersonHomeCityId,

                            c.CityName,

                            p.PersonHomeCountryId,

                            co.CountryName,

                            p.PersonHomeEmail,

                            p.PersonHomePhone,

                            p.PersonId,

                            p.PersonLastName,

                            p.PersonMiddleName,

                            p.PersonPositionId,

                            po.PositionName,

                            PersonName = p.PersonFirstName + ” ” + p.PersonMiddleName + ” ” + p.PersonLastName

                        });

            var orderData = data.OrderBy(p=>p.PersonName);

            if (sortDirection == “ascending”)

            {

                switch (sortExpression)

                {

                    case “CityName”:

                        return data.OrderBy(p => p.CityName);

                    case “ClassificationName”:

                        return data.OrderBy(p => p.ClassificationName);

                    case “CompanyName”:

                        return data.OrderBy(p => p.CompanyName);

                    case “CountryName”:

                        return data.OrderBy(p => p.CountryName);

                    case “PersonBirthDate”:

                        return data.OrderBy(p => p.PersonBirthDate);

                    case “PersonFirstName”:

                        return data.OrderBy(p => p.PersonFirstName);

                    case “PersonGender”:

                        return data.OrderBy(p => p.PersonGender);

                    case “PersonHomeAddress”:

                        return data.OrderBy(p => p.PersonHomeAddress);

                    case “PersonHomeCellularPhone”:

                        return data.OrderBy(p => p.PersonHomeCellularPhone);

                    case “PersonHomeEmail”:

                        return data.OrderBy(p => p.PersonHomeEmail);

                    case “PersonHomePhone”:

                        return data.OrderBy(p => p.PersonHomePhone);

                    case “PersonLastName”:

                        return data.OrderBy(p => p.PersonLastName);

                    case “PersonMiddleName”:

                        return data.OrderBy(p => p.PersonMiddleName);

                    case “PersonName”:

                        return data.OrderBy(p => p.PersonName);

                    case “PositionName”:

                        return data.OrderBy(p => p.PositionName);

                }

            }

            else

            {

                switch (sortExpression)

                {

                    case “CityName”:

                        return data.OrderByDescending(p => p.CityName);

                    case “ClassificationName”:

                        return data.OrderByDescending(p => p.ClassificationName);

                    case “CompanyName”:

                        return data.OrderByDescending(p => p.CompanyName);

                    case “CountryName”:

                        return data.OrderByDescending(p => p.CountryName);

                    case “PersonBirthDate”:

                        return data.OrderByDescending(p => p.PersonBirthDate);

                    case “PersonFirstName”:

                        return data.OrderByDescending(p => p.PersonFirstName);

                    case “PersonGender”:

                        return data.OrderByDescending(p => p.PersonGender);

                    case “PersonHomeAddress”:

                        return data.OrderByDescending(p => p.PersonHomeAddress);

                    case “PersonHomeCellularPhone”:

                        return data.OrderByDescending(p => p.PersonHomeCellularPhone);

                    case “PersonHomeEmail”:

                        return data.OrderByDescending(p => p.PersonHomeEmail);

                    case “PersonHomePhone”:

                        return data.OrderByDescending(p => p.PersonHomePhone);

                    case “PersonLastName”:

                        return data.OrderByDescending(p => p.PersonLastName);

                    case “PersonMiddleName”:

                        return data.OrderByDescending(p => p.PersonMiddleName);

                    case “PersonName”:

                        return data.OrderByDescending(p => p.PersonName);

                    case “PositionName”:

                        return data.OrderByDescending(p => p.PositionName);

                }

            }

            return personQuery;

        }

    }

    public class PersonClass : PersonInterface

    {

        List<tblPerson> personList;

        tblPerson person;

        TestDBEntitiesConnectionString dbEntity;

        string connString = ConfigurationManager.ConnectionStrings["TestDBEntitiesConnectionString"].ConnectionString;

        public PersonClass()

        {

            personList = new List<tblPerson>();

            person = new tblPerson();

            dbEntity = new TestDBEntitiesConnectionString(connString);

        }

        public List<tblPerson> RetrievePersonList()

        {

            personList = (from p in dbEntity.tblPersons

                          select p).ToList<tblPerson>();

            return personList;

        }

        public List<tblPerson> RetrievePersonListByName(string name, string sortExpression, string sortDirection)

        {

            List<tblPerson> list = (from p in dbEntity.tblPersons

                          where (p.PersonFirstName + ” ” + p.PersonMiddleName + ” ” + p.PersonLastName).Contains(name)

                          select p).ToList<tblPerson>();

            if (sortDirection == “ascending”)

            {

                switch (sortExpression)

                {

                    case “PersonBirthDate”:

                        personList = list.OrderBy(p => p.PersonBirthDate).ToList<tblPerson>();

                        break;

                    case “PersonFirstName”:

                        personList = list.OrderBy(p => p.PersonFirstName).ToList<tblPerson>();

                        break;

                    case “PersonGender”:

                        personList = list.OrderBy(p => p.PersonGender).ToList<tblPerson>();

                        break;

                    case “PersonHomeAddress”:

                        personList = list.OrderBy(p => p.PersonHomeAddress).ToList<tblPerson>();

                        break;

                    case “PersonHomeCellularPhone”:

                        personList = list.OrderBy(p => p.PersonHomeCellularPhone).ToList<tblPerson>();

                        break;

                    case “PersonHomeEmail”:

                        personList = list.OrderBy(p => p.PersonHomeEmail).ToList<tblPerson>();

                        break;

                    case “PersonHomePhone”:

                        personList = list.OrderBy(p => p.PersonHomePhone).ToList<tblPerson>();

                        break;

                    case “PersonLastName”:

                        personList = list.OrderBy(p => p.PersonLastName).ToList<tblPerson>();

                        break;

                    case “PersonMiddleName”:

                        personList = list.OrderBy(p => p.PersonMiddleName).ToList<tblPerson>();

                        break;

                }

            }

            else

            {

                switch (sortExpression)

                {

                    case “PersonBirthDate”:

                        personList = list.OrderByDescending(p => p.PersonBirthDate).ToList<tblPerson>();

                        break;

                    case “PersonFirstName”:

                        personList = list.OrderByDescending(p => p.PersonFirstName).ToList<tblPerson>();

                        break;

                    case “PersonGender”:

                        personList = list.OrderByDescending(p => p.PersonGender).ToList<tblPerson>();

                        break;

                    case “PersonHomeAddress”:

                        personList = list.OrderByDescending(p => p.PersonHomeAddress).ToList<tblPerson>();

                        break;

                    case “PersonHomeCellularPhone”:

                        personList = list.OrderByDescending(p => p.PersonHomeCellularPhone).ToList<tblPerson>();

                        break;

                    case “PersonHomeEmail”:

                        personList = list.OrderByDescending(p => p.PersonHomeEmail).ToList<tblPerson>();

                        break;

                    case “PersonHomePhone”:

                        personList = list.OrderByDescending(p => p.PersonHomePhone).ToList<tblPerson>();

                        break;

                    case “PersonLastName”:

                        personList = list.OrderByDescending(p => p.PersonLastName).ToList<tblPerson>();

                        break;

                    case “PersonMiddleName”:

                        personList = list.OrderByDescending(p => p.PersonMiddleName).ToList<tblPerson>();

                        break;

                }

            }

            return personList;

        }

        public tblPerson RetrievePersonByID(int id)

        {

            person = (from p in dbEntity.tblPersons

                      where p.PersonId == id

                      select p).First<tblPerson>();

            return person;

        }

        public tblPerson RetrievePersonByName(string name)

        {

            person = (from p in dbEntity.tblPersons

                      where (p.PersonFirstName + ” ” + p.PersonMiddleName + ” ” + p.PersonLastName) == name

                      select p).First<tblPerson>();

            return person;

        }

        public int CreatePerson(tblPerson persons)

        {

            try

            {

                dbEntity.AddTotblPersons(persons);

                dbEntity.SaveChanges();

                person = (from p in dbEntity.tblPersons

                          where p.PersonLastName == persons.PersonLastName & p.PersonMiddleName == persons.PersonMiddleName & p.PersonFirstName == persons.PersonFirstName

                          select p).First<tblPerson>();

            }

            catch (System.Exception ex)

            {

                throw ex;

            }

            return person == null ? 0 : person.PersonId;

        }

        public int UpdatePerson(tblPerson persons)

        {

            person = (from p in dbEntity.tblPersons

                       where p.PersonId == persons.PersonId

                       select p).First<tblPerson>();

            person.PersonBirthDate = persons.PersonBirthDate;

            person.PersonClassificationId = persons.PersonClassificationId;

            person.PersonCompanyId = persons.PersonCompanyId;

            person.PersonFirstName = persons.PersonFirstName;

            person.PersonGender = persons.PersonGender;

            person.PersonHomeAddress = persons.PersonHomeAddress;

            person.PersonHomeCellularPhone = persons.PersonHomeCellularPhone;

            person.PersonHomeCityId = persons.PersonHomeCityId;

            person.PersonHomeCountryId = persons.PersonHomeCountryId;

            person.PersonHomeEmail = persons.PersonHomeEmail;

            person.PersonHomePhone = persons.PersonHomePhone;

            person.PersonLastName = persons.PersonLastName;

            person.PersonMiddleName = persons.PersonMiddleName;

            person.PersonPositionId = persons.PersonPositionId;

            return dbEntity.SaveChanges();

        }

        public int DeletePerson(int id)

        {

            person = (from p in dbEntity.tblPersons

                       where p.PersonId == id

                       select p).First<tblPerson>();

            dbEntity.DeleteObject(person);

            return dbEntity.SaveChanges();

        }

    }

}

To create the UI Part, here is the markup for designer part,

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true” CodeFile=”PersonPage.aspx.cs” Inherits=”PersonPage” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” Runat=”Server”>

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” Runat=”Server”>

    <asp:ScriptManager ID=”ScriptManager” runat=”server” ></asp:ScriptManager>

    <asp:UpdatePanel ID=”upPerson” runat=”server” UpdateMode=”Conditional”>

        <ContentTemplate>

            <table>

                <tr>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                </tr>

                <tr>

                    <td>

                    </td>

                    <td colspan=”2″ align=”center”>

                        <asp:MultiView ID=”mvPerson” runat=”server” ActiveViewIndex=”0″>

                            <asp:View ID=”vwCreatePerson” runat=”server”>

                                <table width=”100%”>

                                    <tr>

                                        <td>

                                        </td>

                                        <td colspan=”2″>

                                            <asp:ValidationSummary ID=”vsCreatePerson” runat=”server”

                                                ValidationGroup=”validateCreatePerson” DisplayMode=”BulletList”

                                                ForeColor=”Red” />

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            First Name:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtFirstName” runat=”server” MaxLength=”20″ Width=”250px” ></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvFirstName” runat=”server”

                                                ControlToValidate=”txtFirstName” ErrorMessage=”First name is required.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Last Name:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtLastName” runat=”server” MaxLength=”20″ Width=”250px”></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvLastName” runat=”server”

                                                ControlToValidate=”txtLastName” ErrorMessage=”Last Name is required.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Middle Name:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtMiddleName” runat=”server” MaxLength=”20″ Width=”250px”></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvMiddleName” runat=”server”

                                                ControlToValidate=”txtMiddleName” ErrorMessage=”Middle Name is required.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Gender:

                                        </td>

                                        <td align=”left”>

                                            <asp:RadioButtonList ID=”rdlGender” runat=”server” Width=”250px”>

                                                <asp:ListItem Text=”Male” Value=”M”></asp:ListItem>

                                                <asp:ListItem Text=”Female” Value=”F”></asp:ListItem>

                                            </asp:RadioButtonList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Birth Date:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtBirthDate” runat=”server” Width=”250px”></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvBirthDate” runat=”server”

                                                ControlToValidate=”txtBirthDate” ErrorMessage=”Birth Date is required.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”>*</asp:RequiredFieldValidator>

                                            <asp:CompareValidator ID=”cvBirthDate” runat=”server”

                                                ControlToValidate=”txtBirthDate” ErrorMessage=” Birth Date is not valid date.”

                                                ForeColor=”Red”  ValidationGroup=”validateCreatePerson”>*</asp:CompareValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Address:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtAddress” runat=”server” TextMode=”MultiLine” Width=”250px”></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvAddress” runat=”server”

                                                ControlToValidate=”txtAddress” ErrorMessage=”Address is required.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            City:

                                        </td>

                                        <td align=”left”>

                                            <asp:DropDownList ID=”ddlCity” runat=”server” Width=”250px”></asp:DropDownList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Country:

                                        </td>

                                        <td align=”left”>

                                            <asp:DropDownList ID=”ddlCountry” runat=”server” Width=”250px”></asp:DropDownList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            E-Mail Address:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtEmailAddress” runat=”server” Width=”250px”></asp:TextBox>

                                            <asp:RegularExpressionValidator ID=”revEmailAddress” runat=”server”

                                                ControlToValidate=”txtEmailAddress” ErrorMessage=”E-mail Address is not valid.”

                                                ForeColor=”Red” ValidationGroup=”validateCreatePerson”

                                                ValidationExpression=”\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”>*</asp:RegularExpressionValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Home Phone Number:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtHomePhoneNo” runat=”server” Width=”250px”></asp:TextBox>

                                            <asp:RegularExpressionValidator ID=”revPhoneNo” runat=”server” ValidationGroup=”validateCreatePerson”

                                                ControlToValidate=”txtHomePhoneNo” ErrorMessage=”Phone number is not in correct format.”

                                                ForeColor=”Red” ValidationExpression=”((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}”>*</asp:RegularExpressionValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Cellular Phone Number:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtCellularPhoneNo” runat=”server” Width=”250px”></asp:TextBox>

                                            <asp:RegularExpressionValidator ID=”revCellularNo” runat=”server”

                                                ErrorMessage=”Cellular Number is not in correct format.” ValidationGroup=”validateCreatePerson”

                                                ControlToValidate=”txtCellularPhoneNo” ForeColor=”Red”

                                                ValidationExpression=”((\d{3} ?)|(\d{3}-))?\d{3}-\d{4}”>*</asp:RegularExpressionValidator>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Classification:

                                        </td>

                                        <td align=”left”>

                                            <asp:DropDownList ID=”ddlClassification” runat=”server” Width=”250px”></asp:DropDownList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Company:

                                        </td>

                                        <td align=”left”>

                                            <asp:DropDownList ID=”ddlCompany” runat=”server” Width=”250px”></asp:DropDownList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Position:

                                        </td>

                                        <td align=”left”>

                                            <asp:DropDownList ID=”ddlPosition” runat=”server” Width=”250px”></asp:DropDownList>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td align=”left”>

                                            <asp:Button ID=”btnSavePerson” runat=”server” Text=”Save”

                                                ValidationGroup=”validateCreatePerson” onclick=”btnSavePerson_Click” />

                                            <asp:Button ID=”btnCancelPerson” runat=”server” Text=”Cancel”

                                                onclick=”btnCancelPerson_Click” />

                                            <asp:Button ID=”btnShowSearchPerson” runat=”server” Text=”Search Person”

                                                onclick=”btnShowSearchPerson_Click” />

                                        </td>

                                        <td

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                </table>

                            </asp:View>

                            <asp:View ID=”vwSearchPerson” runat=”server”>

                                <table>

                                    <tr>

                                        <td>

                                        </td>

                                        <td colspan=”2″>

                                            <asp:ValidationSummary ID=”vsSearchPerson” runat=”server” DisplayMode=”BulletList” ValidationGroup=”validateSearchPerson” />

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td align=”right”>

                                            Search Person:

                                        </td>

                                        <td align=”left”>

                                            <asp:TextBox ID=”txtSearchPerson” runat=”server”></asp:TextBox>

                                            <asp:Button ID=”btnSearchPerson” runat=”server” Text=”Search”

                                                onclick=”btnSearchPerson_Click” />

                                            <asp:Button ID=”btnCreatePerson” runat=”server” Text=”Create Person”

                                                onclick=”btnCreatePerson_Click” />

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td colspan=”2″>

                                            <asp:GridView ID=”gvPerson” runat=”server” AllowPaging=”True”

                                                AllowSorting=”True” AutoGenerateColumns=”False”

                                                onpageindexchanging=”gvPerson_PageIndexChanging”

                                                onrowcancelingedit=”gvPerson_RowCancelingEdit”

                                                onrowdeleting=”gvPerson_RowDeleting” onrowediting=”gvPerson_RowEditing”

                                                onrowupdating=”gvPerson_RowUpdating” onsorting=”gvPerson_Sorting”>

                                                <Columns>

                                                    <asp:BoundField DataField=”PersonID” HeaderText=”Person ID” ReadOnly=”True”

                                                        SortExpression=”PersonID” Visible=”False” />

                                                    <asp:TemplateField HeaderText=”First Name” SortExpression=”PersonFirstName”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridFirstName” runat=”server” Text='<%# Bind(“PersonFirstName”) %>’ MaxLength=”20″></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID=”rfvGridFirstName” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridFirstName” ErrorMessage=”First name is required.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:RequiredFieldValidator> 

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridFirstName” runat=”server” Text='<%# Bind(“PersonFirstName”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridFirstName” runat=”server” Text='<%# Bind(“PersonFirstName”) %>’ MaxLength=”20″ Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Middle Name” SortExpression=”PersonMiddleName”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridMiddleName” runat=”server” Text='<%# Bind(“PersonMiddleName”) %>’ MaxLength=”20″></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID=”rfvGridMiddleName” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridMiddleName” ErrorMessage=”Middle Name is required.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:RequiredFieldValidator>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridMiddleName” runat=”server” Text='<%# Bind(“PersonMiddleName”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridMiddleName” runat=”server” Text='<%# Bind(“PersonMiddleName”) %>’ MaxLength=”20″ Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Last Name” SortExpression=”PersonLastName”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridLastName” runat=”server” Text='<%# Bind(“PersonLastName”) %>’ MaxLength=”20″></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID=”rfvGridLastName” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridLastName” ErrorMessage=”Last Name is required.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:RequiredFieldValidator>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridLastName” runat=”server” Text='<%# Bind(“PersonLastName”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridLastName” runat=”server” Text='<%# Bind(“PersonLastName”) %>’ MaxLength=”20″ visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Gender” SortExpression=”PersonGender”>

                                                        <EditItemTemplate>

                                                            <asp:RadioButtonList ID=”rblGridGender” runat=”server”>

                                                                <asp:ListItem Text=”Male” Value=”M” ></asp:ListItem>

                                                                <asp:ListItem Text=”Female” Value=”F”></asp:ListItem>

                                                            </asp:RadioButtonList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridGender” runat=”server” Text='<%# Bind(“PersonGender”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Birth Date” SortExpression=”PersonBirthDate”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridBirthDate” runat=”server” Text='<%# Bind(“PersonBirthDate”) %>’></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID=”rfvGridBirthDate” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridBirthDate” ErrorMessage=”Birth date is required.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:RequiredFieldValidator>

                                                            <asp:CompareValidator ID=”cvGridBirthDate” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridBirthDate” ErrorMessage=”Birth date is not valid date.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:CompareValidator>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridBirthDate” runat=”server” Text='<%# Bind(“PersonBirthDate”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridBirthDate” runat=”server” Text='<%# Bind(“PersonBirthDate”) %>’ Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Address” SortExpression=”PersonHomeAddress”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridHomeAddress” runat=”server” Text='<%# Bind(“PersonHomeAddress”) %>’ TextMode=”MultiLine”></asp:TextBox>

                                                            <asp:RequiredFieldValidator ID=”rfvGridAddress” runat=”server” ForeColor=”Red” ControlToValidate=”txtGridHomeAddress” ErrorMessage=”Address is required.” Text=”*” ValidationGroup=”validateSearchPerson”></asp:RequiredFieldValidator>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”blGridAddress” runat=”server” Text='<%# Bind(“PersonHomeAddress”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridHomeAddress” runat=”server” Text='<%# Bind(“PersonHomeAddress”) %>’ TextMode=”MultiLine” Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”City ID” SortExpression=”PersonHomeCityID”

                                                        Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCityID” runat=”server” Text='<%# Bind(“CityID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCityID” runat=”server” Text='<%# Bind(“CityID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”City” SortExpression=”CityName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridCity” runat=”server” ></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCity” runat=”server” Text='<%# Bind(“CityName”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Country ID” SortExpression=”PersonHomeCountryID”

                                                        Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCountryID” runat=”server” Text='<%# Bind(“CountryID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCountryID” runat=”server” Text='<%# Bind(“CountryID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Country” SortExpression=”CountryName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridCountry” runat=”server” ></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCountry” runat=”server” Text='<%# Bind(“CountryName”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”E-mail Address” SortExpression=”PersonHomeEmail”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridEmail” runat=”server” Text='<%# Bind(“PersonHomeEmail”) %>’></asp:TextBox>

                                                            <asp:RegularExpressionValidator ID=”revGridEmailAddress” runat=”server”

                                                ControlToValidate=”txtGridEmail” ErrorMessage=”E-mail Address is not valid.”

                                                ForeColor=”Red” ValidationGroup=”validateSearchPerson”

                                                ValidationExpression=”\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”>*</asp:RegularExpressionValidator>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridEmail” runat=”server” Text='<%# Bind(“PersonHomeEmail”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Phone No” SortExpression=”PersonHomePhone”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridHomePhone” runat=”server” Text='<%# Bind(“PersonHomePhone”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridHomePhone” runat=”server” Text='<%# Bind(“PersonHomePhone”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Cellular Phone”

                                                        SortExpression=”PersonHomeCellularPhone”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCellularPhone” runat=”server” Text='<%# Bind(“PersonHomeCellularPhone”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCellularPhone” runat=”server” Text='<%# Bind(“PersonHomeCellularPhone”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Classification ID”

                                                        SortExpression=”PersonClassificationID” Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridClassificationID” runat=”server” Text='<%# Bind(“ClassificationID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridClassificationID” runat=”server” Text='<%# Bind(“ClassificationID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Classification”

                                                        SortExpression=”ClassificationName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridClassification” runat=”server” ></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridClassification” runat=”server” Text='<%# Bind(“ClassificationName”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Company ID” SortExpression=”PersonCompanyID”

                                                        Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCompanyID” runat=”server” Text='<%# Bind(“CompanyID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCompanyID” runat=”server” Text='<%# Bind(“CompanyID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Company” SortExpression=”CompanyName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridCompany” runat=”server” ></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCompany” runat=”server” Text='<%# Bind(“CompanyName”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Position ID” SortExpression=”PersonPositionID”

                                                        Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridPositionID” runat=”server” Text='<%# Bind(“PositionID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridPositionID” runat=”server” Text='<%# Bind(“PositionID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Position” SortExpression=”PositionName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridPosition” runat=”server”></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridPosition” runat=”server” Text='<%# Bind(“PositionName”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField ShowHeader=”False”>

                                                        <EditItemTemplate>

                                                            <asp:Button ID=”btnGridUpdatePerson” runat=”server” CausesValidation=”True”

                                                                CommandName=”Update” Text=”Update” ValidationGroup=”validateSearchPerson” />

                                                            &nbsp;<asp:Button ID=”btnGridCancelPerson” runat=”server” CausesValidation=”False”

                                                                CommandName=”Cancel” Text=”Cancel” />

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Button ID=”btnGridEditPerson” runat=”server” CausesValidation=”False”

                                                                CommandName=”Edit” Text=”Edit” />

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField ShowHeader=”False”>

                                                        <ItemTemplate>

                                                            <asp:Button ID=”btnGridDeletePerson” runat=”server” CausesValidation=”False”

                                                                CommandName=”Delete” Text=”Delete” />

                                                            <asp:HiddenField ID=”hfPersonID” runat=”server” Value='<%# Bind(“PersonID”) %>’ />

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                </Columns>

                                            </asp:GridView>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                </table>

                            </asp:View>

                        </asp:MultiView>

                    </td>

                    <td>

                    </td>

                </tr>

                <tr>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                </tr>

            </table>

        </ContentTemplate>

        <Triggers>

        </Triggers>

    </asp:UpdatePanel>

</asp:Content>

Here is the code part,

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using MyLinqToEntityClassLibrary;

public partial class PersonPage : System.Web.UI.Page

{

    #region “Variables”

    List<tblCity> cityList;

    List<tblClassification> classificationList;

    List<tblCompany> companyList;

    List<tblCountry> countryList;

    List<tblPerson> personList;

    List<tblPosition> positionList;

    tblPerson person;

    CityClass cityBll;

    CountryClass countryBll;

    CompanyClass companyBll;

    ClassificationClass classificationBll;

    PersonClass personBll;

    PositionClass positionBll;

    IOrderedQueryable personQry;

    List<PersonClassificationCompanyCityCountryPosition> personClassificationCompanyCityCountryPositionList;

    PersonClassificationCompanyCityCountryPositionBLL personClassificationCompanyCityCountryPositionBll;

    #endregion

    #region “Methods”

    private void MessageBox(string message)

    {

        ScriptManager.RegisterStartupScript(this, this.GetType(), “onclick”, “alert(‘” + message + “‘)”, true);

    }

    private void ResetEntry()

    {

        this.txtAddress.Text = string.Empty;

        this.txtBirthDate.Text = string.Empty;

        this.txtCellularPhoneNo.Text = string.Empty;

        this.txtEmailAddress.Text = string.Empty;

        this.txtFirstName.Text = string.Empty;

        this.txtHomePhoneNo.Text = string.Empty;

        this.txtLastName.Text = string.Empty;

        this.txtMiddleName.Text = string.Empty;

        this.txtSearchPerson.Text = string.Empty;

        this.ddlCity.SelectedIndex = -1;

        this.ddlClassification.SelectedIndex = -1;

        this.ddlCompany.SelectedIndex = -1;

        this.ddlCountry.SelectedIndex = -1;

        this.ddlPosition.SelectedIndex = -1;

    }

    private void PopulateGridView()

    {

        try

        {

            personClassificationCompanyCityCountryPositionList = personClassificationCompanyCityCountryPositionBll.RetrievePersonNameListByName(this.txtSearchPerson.Text.Trim(), Convert.ToString(Session["SortExpression"]), Convert.ToString(Session["SortDirection"]));

            this.gvPerson.DataSource = personClassificationCompanyCityCountryPositionList;

            this.gvPerson.DataBind();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void SetGender(RadioButtonList rbl, string gender)

    {

        rbl.SelectedValue = gender;

    }

    private void PopulateCityList()

    {

        try

        {

            cityList = cityBll.RetrieveCityList();

            this.ddlCity.DataSource = cityList;

            this.ddlCity.DataTextField = “CityName”;

            this.ddlCity.DataValueField = “CityID”;

            this.ddlCity.DataBind(); 

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateGridCityList(DropDownList ddl, string id)

    {

        try

        {

            cityList = cityBll.RetrieveCityList();

            ddl.DataSource = cityList;

            ddl.DataTextField = “CityName”;

            ddl.DataValueField = “CityID”;

            ddl.DataBind();

            ddl.SelectedValue = id;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateCountryList()

    {

        try

        {

            countryList = countryBll.RetrieveCountryList();

            this.ddlCountry.DataSource = countryList;

            this.ddlCountry.DataTextField = “CountryName”;

            this.ddlCountry.DataValueField = “CountryID”;

            this.ddlCountry.DataBind();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateGridCountryList(DropDownList ddl, string id)

    {

        try

        {

            countryList = countryBll.RetrieveCountryList();

            ddl.DataSource = countryList;

            ddl.DataTextField = “CountryName”;

            ddl.DataValueField = “CountryID”;

            ddl.DataBind();

            ddl.SelectedValue = id;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateCompanyList()

    {

        try

        {

            companyList = companyBll.RetrieveCompanyList();

            this.ddlCompany.DataSource = companyList;

            this.ddlCompany.DataTextField = “CompanyName”;

            this.ddlCompany.DataValueField = “CompanyID”;

            this.ddlCompany.DataBind(); 

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateGridCompanyList(DropDownList ddl, string id)

    {

        try

        {

            companyList = companyBll.RetrieveCompanyList();

            ddl.DataSource = companyList;

            ddl.DataTextField = “CompanyName”;

            ddl.DataValueField = “CompanyID”;

            ddl.DataBind();

            ddl.SelectedValue = id;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateClassificationList()

    {

        try

        {

            classificationList = classificationBll.RetrieveClassificationList();

            this.ddlClassification.DataSource = classificationList;

            this.ddlClassification.DataTextField = “ClassificationName”;

            this.ddlClassification.DataValueField = “ClassificationID”;

            this.ddlClassification.DataBind();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateGridClassificationList(DropDownList ddl, string id)

    {

        try

        {

            classificationList = classificationBll.RetrieveClassificationList();

            ddl.DataSource = classificationList;

            ddl.DataTextField = “ClassificationName”;

            ddl.DataValueField = “ClassificationID”;

            ddl.DataBind();

            ddl.SelectedValue = id;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulatePositionList()

    {

        try

        {

            positionList = positionBll.RetrievePositionList();

            this.ddlPosition.DataSource = positionList;

            this.ddlPosition.DataTextField = “PositionName”;

            this.ddlPosition.DataValueField = “PositionID”;

            this.ddlPosition.DataBind();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private void PopulateGridPositionList(DropDownList ddl, string id)

    {

        try

        {

            positionList = positionBll.RetrievePositionList();

            ddl.DataSource = positionList;

            ddl.DataTextField = “PositionName”;

            ddl.DataValueField = “PositionID”;

            ddl.DataBind();

            ddl.SelectedValue = id;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    private bool CheckForDuplicatePerson(string name, int id, bool IsEdit)

    {

        bool duplicate = false;

        try

        {

            personList = personBll.RetrievePersonListByName(name, Convert.ToString(Session["SortExpression"]), Convert.ToString(Session["SortDirection"]));

            if (IsEdit)

            {

                person = personList.Find(p => p.PersonId != id & (p.PersonFirstName + ” ” + p.PersonMiddleName + ” ” + p.PersonLastName) == name);

                if (person != null)

                    duplicate = true;

            }

            else

            {

                if (personList != null & personList.Count > 0)

                    duplicate = true;

            }

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

        return duplicate;

    }

    private bool CheckForDependency(int id)

    {

        bool dependency = false;

        try

        {

            if (companyList == null | companyList.Count == 0 )

                companyList = companyBll.RetrieveCompanyList();

            tblCompany company = companyList.Find(c => c.CompanyContactPersonId == id);

            if (company != null)

                dependency = true;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

        return dependency;

    }

    #endregion

    #region “Events”

    public void Page_Init(object sender, EventArgs e)

    {

        cityList = new List<tblCity>();

        classificationList = new List<tblClassification>();

        companyList = new List<tblCompany>();

        countryList = new List<tblCountry>();

        personList = new List<tblPerson>();

        positionList = new List<tblPosition>();

        person = new tblPerson();

        cityBll = new CityClass();

        countryBll = new CountryClass();

        companyBll = new CompanyClass();

        classificationBll = new ClassificationClass();

        personBll = new PersonClass();

        positionBll = new PositionClass();

        personClassificationCompanyCityCountryPositionList = new List<PersonClassificationCompanyCityCountryPosition>();

        personClassificationCompanyCityCountryPositionBll = new PersonClassificationCompanyCityCountryPositionBLL();

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        try

        {

            if (!this.Page.IsPostBack)

            {

                PopulateCityList();

                PopulateClassificationList();

                PopulateCompanyList();

                PopulateCountryList();

                PopulatePositionList();

                this.cvBirthDate.Operator = ValidationCompareOperator.LessThanEqual;

                this.cvBirthDate.ValueToCompare = DateTime.Now.AddYears(-18).ToShortDateString();

                Response.Write(DateTime.Now.AddYears(-18).ToShortDateString());

            }

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void btnSavePerson_Click(object sender, EventArgs e)

    {

        try

        {

            person = new tblPerson();

            person.PersonBirthDate = Convert.ToDateTime(this.txtBirthDate.Text);

            person.PersonClassificationId = Convert.ToInt32(this.ddlClassification.SelectedValue);

            person.PersonCompanyId = Convert.ToInt32(this.ddlCompany.SelectedValue);

            person.PersonFirstName = this.txtFirstName.Text.Trim();

            person.PersonGender = this.rdlGender.SelectedValue;

            person.PersonHomeAddress = this.txtAddress.Text.Trim();

            person.PersonHomeCellularPhone = this.txtCellularPhoneNo.Text.Trim().Replace(” “, “”).Replace(“-“, “”);

            person.PersonHomeCityId = Convert.ToInt32(this.ddlCity.SelectedValue);

            person.PersonHomeCountryId = Convert.ToInt32(this.ddlCountry.SelectedValue);

            person.PersonHomeEmail = this.txtEmailAddress.Text.Trim();

            person.PersonHomePhone = this.txtHomePhoneNo.Text.Trim().Replace(“(“,””).Replace(“)”,””).Replace(” “,””).Replace(“-“,””);

            person.PersonLastName = this.txtLastName.Text.Trim();

            person.PersonMiddleName = this.txtMiddleName.Text.Trim();

            person.PersonPositionId = Convert.ToInt32(this.ddlPosition.SelectedValue);

            if (CheckForDuplicatePerson(person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName, 0, false) == false)

            {

                int result = personBll.CreatePerson(person);

                if (result > 0)

                    MessageBox(“Successfully add new person, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

                else

                    MessageBox(“Failed to add new person, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

            }

            else

                MessageBox(“Duplicate person’s name, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void btnCancelPerson_Click(object sender, EventArgs e)

    {

        try

        {

            ResetEntry();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void btnShowSearchPerson_Click(object sender, EventArgs e)

    {

        try

        {

            this.mvPerson.ActiveViewIndex = 1;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void btnSearchPerson_Click(object sender, EventArgs e)

    {

        try

        {

            Session["SortDirection"] = “ascending”;

            Session["SortExpression"] = “PersonFirstName”;

            PopulateGridView();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void btnCreatePerson_Click(object sender, EventArgs e)

    {

        try

        {

            this.mvPerson.ActiveViewIndex = 0;

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        try

        {

            this.gvPerson.PageIndex = e.NewPageIndex;

            PopulateGridView();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        try

        {

            this.gvPerson.EditIndex = -1;

            PopulateGridView();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        try

        {

            HiddenField hf = (HiddenField)this.gvPerson.Rows[e.RowIndex].Cells[21].FindControl(“hfPersonID”);

            if (CheckForDependency(Convert.ToInt32(hf.Value)))

                MessageBox(“There is a dependency on other table. It cannot be deleted before deleting the child first.”);

            else

            {

                int result = personBll.DeletePerson(Convert.ToInt32(hf.Value));

                if (result > 0)

                    MessageBox(“Successfully deleted this person.”);

                else

                    MessageBox(“Failed to delete this person.”);

                PopulateGridView();

            }

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_RowEditing(object sender, GridViewEditEventArgs e)

    {

        try

        {

            this.gvPerson.EditIndex = e.NewEditIndex;

            PopulateGridView();

            RadioButtonList gender = (RadioButtonList)this.gvPerson.Rows[e.NewEditIndex].Cells[4].FindControl(“rblGridGender”);

            TextBox cityID = (TextBox)this.gvPerson.Rows[e.NewEditIndex].Cells[7].FindControl(“txtGridCityID”);

            DropDownList city = (DropDownList)this.gvPerson.Rows[e.NewEditIndex].Cells[8].FindControl(“ddlGridCity”);

            TextBox countryId = (TextBox)this.gvPerson.Rows[e.NewEditIndex].Cells[9].FindControl(“txtGridCountryID”);

            DropDownList country = (DropDownList)this.gvPerson.Rows[e.NewEditIndex].Cells[10].FindControl(“ddlGridCountry”);

            TextBox classificationId = (TextBox)this.gvPerson.Rows[e.NewEditIndex].Cells[14].FindControl(“txtGridClassificationID”);

            DropDownList classification = (DropDownList)this.gvPerson.Rows[e.NewEditIndex].Cells[15].FindControl(“ddlGridClassification”);

            TextBox companyId = (TextBox)this.gvPerson.Rows[e.NewEditIndex].Cells[16].FindControl(“txtGridCompanyID”);

            DropDownList company = (DropDownList)this.gvPerson.Rows[e.NewEditIndex].Cells[17].FindControl(“ddlGridCompany”);

            TextBox positionId = (TextBox)this.gvPerson.Rows[e.NewEditIndex].Cells[18].FindControl(“txtGridPositionID”);

            DropDownList position = (DropDownList)this.gvPerson.Rows[e.NewEditIndex].Cells[19].FindControl(“ddlGridPosition”);

            HiddenField hf = (HiddenField)this.gvPerson.Rows[e.NewEditIndex].Cells[21].FindControl(“hfPersonID”);

            RegularExpressionValidator revEmail = (RegularExpressionValidator)this.gvPerson.Rows[e.NewEditIndex].Cells[11].FindControl(“revGridEmailAddress”);

            CompareValidator cv = (CompareValidator)this.gvPerson.Rows[e.NewEditIndex].Cells[5].FindControl(“cvGridBirthDate”);

            cv.Operator = ValidationCompareOperator.LessThanEqual;

            cv.ValueToCompare = DateTime.Now.AddYears(-18).ToShortDateString();

            PopulateGridCityList(city, cityID.Text.Trim());

            PopulateGridClassificationList(classification, classificationId.Text.Trim());

            PopulateGridCompanyList(company, companyId.Text.Trim());

            PopulateGridCountryList(country, countryId.Text.Trim());

            PopulateGridPositionList(position, positionId.Text.Trim());

            if (personClassificationCompanyCityCountryPositionList == null)

                personClassificationCompanyCityCountryPositionList = personClassificationCompanyCityCountryPositionBll.RetrievePersonNameListByName(this.txtSearchPerson.Text.Trim(), Convert.ToString(Session["SortExpression"]), Convert.ToString(Session["SortDirection"]));

            foreach (PersonClassificationCompanyCityCountryPosition pp in personClassificationCompanyCityCountryPositionList)

            {

                if (pp.PersonID == Convert.ToInt32(hf.Value))

                    SetGender(gender, pp.PersonGender);

            }

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        try

        {

            TextBox firstname = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[1].FindControl(“txtGridFirstName”);

            TextBox middleName = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[2].FindControl(“txtGridMiddleName”);

            TextBox lastName = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[3].FindControl(“txtGridLastName”);

            RadioButtonList gender = (RadioButtonList)this.gvPerson.Rows[e.RowIndex].Cells[4].FindControl(“rblGridGender”);

            TextBox birthDate = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[5].FindControl(“txtGridBirthDate”);

            TextBox address = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[6].FindControl(“txtGridHomeAddress”);

            TextBox cityID = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[7].FindControl(“txtGridCityID”);

            DropDownList city = (DropDownList)this.gvPerson.Rows[e.RowIndex].Cells[8].FindControl(“ddlGridCity”);

            TextBox countryId = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[9].FindControl(“txtGridCountryID”);

            DropDownList country = (DropDownList)this.gvPerson.Rows[e.RowIndex].Cells[10].FindControl(“ddlGridCountry”);

            TextBox email = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[11].FindControl(“txtGridEmail”);

            TextBox phone = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[12].FindControl(“txtGridHomePhone”);

            TextBox cellular = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[13].FindControl(“txtGridCellularPhone”);

            TextBox classificationId = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[14].FindControl(“txtGridClassificationID”);

            DropDownList classification = (DropDownList)this.gvPerson.Rows[e.RowIndex].Cells[15].FindControl(“ddlGridClassification”);

            TextBox companyId = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[16].FindControl(“txtGridCompanyID”);

            DropDownList company = (DropDownList)this.gvPerson.Rows[e.RowIndex].Cells[17].FindControl(“ddlGridCompany”);

            TextBox positionId = (TextBox)this.gvPerson.Rows[e.RowIndex].Cells[18].FindControl(“txtGridPositionID”);

            DropDownList position = (DropDownList)this.gvPerson.Rows[e.RowIndex].Cells[19].FindControl(“ddlGridPosition”);

            HiddenField hf = (HiddenField)this.gvPerson.Rows[e.RowIndex].Cells[21].FindControl(“hfPersonID”);

            if (CheckForDuplicatePerson(firstname + ” ” + middleName + ” ” + lastName, Convert.ToInt32(hf.Value), true) == false)

            {

                person = personBll.RetrievePersonByID(Convert.ToInt32(hf.Value));

                person.PersonBirthDate = Convert.ToDateTime( birthDate.Text.Trim());

                person.PersonClassificationId = Convert.ToInt32(classification.SelectedValue);

                person.PersonCompanyId = Convert.ToInt32(company.SelectedValue);

                person.PersonFirstName = firstname.Text.Trim();

                person.PersonGender = gender.SelectedValue;

                person.PersonHomeAddress = address.Text.Trim();

                person.PersonHomeCellularPhone = cellular.Text.Trim();

                person.PersonHomeCityId = Convert.ToInt32(city.SelectedValue);

                person.PersonHomeCountryId = Convert.ToInt32(country.SelectedValue);

                person.PersonHomeEmail = email.Text.Trim();

                person.PersonHomePhone = phone.Text.Trim().Replace(“(“, “”).Replace(“)”, “”).Replace(“-“, “”).Replace(” “, “”);

                person.PersonId = Convert.ToInt32(hf.Value);

                person.PersonLastName = lastName.Text.Trim();

                person.PersonMiddleName = middleName.Text.Trim();

                person.PersonPositionId = Convert.ToInt32(position.SelectedValue);

                int result = personBll.UpdatePerson(person);

                if (result > 0)

                    MessageBox(” Successfully update this person, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

                else

                    MessageBox(“Failed to update this person, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

                this.gvPerson.EditIndex = -1;

                PopulateGridView();

            }

            else

                MessageBox(“Duplicate person, ” + person.PersonFirstName + ” ” + person.PersonMiddleName + ” ” + person.PersonLastName);

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    protected void gvPerson_Sorting(object sender, GridViewSortEventArgs e)

    {

        try

        {

            if (Convert.ToString(Session["SortDirection"]) == “ascending”)

            {

                e.SortDirection = SortDirection.Descending;

                Session["SortDirection"] = SortDirection.Descending.ToString();

            }

            else

            {

                e.SortDirection = SortDirection.Ascending;

                Session["SortDirection"] = SortDirection.Ascending.ToString();

            }

            Session["SortExpression"] = e.SortExpression;

            PopulateGridView();

        }

        catch (System.Exception ex)

        {

            MessageBox(ex.Message + ” ” + ex.StackTrace);

        }

    }

    #endregion

}

Posted in .NET Framework 4, C# 4.0 AND ASP.NET 4.0, Linq to Entity | Leave a comment

How to apply CRUD and linq to entity on gridview using ASP.Net 3.5?

Before you start, you need the following software or installer:

Visual Studio 2008 Professional Edition/ Team System Edition

Visual Studio 2008 Service Pack 1

.NET Framework 3.5

.NET Framework 3.5 Service Pack 1

Windows 7 or Windows XP

You need to create a data entry form that will enable you to create an entity or record, retrieve an entity or record, update an existing entity or record, and delete an existing entity or record.

Let us start with creating an entity. First you need to create a multiview control on your designer mode. Then add tables, rows, columns. Create two views, one for creating an entity, the other is for searching or retrieving an entity then perform also updating and deleting an existing entity.

Here is the designer script:

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/DataEntry.Master” AutoEventWireup=”true” CodeBehind=”CityPage.aspx.cs” Inherits=”Web.CityPage” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”Content” runat=”server”>

    <asp:ScriptManager ID=”ScriptManager” runat=”server” ></asp:ScriptManager>

    <asp:UpdatePanel ID=”upCity” runat=”server” UpdateMode=”Conditional”>

        <ContentTemplate>

            <table>

                <tr>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                </tr>

                <tr>

                    <td>

                    </td>

                    <td colspan=”2″>

                        <asp:MultiView ID=”mvCity” runat=”server” ActiveViewIndex=”0″>

                            <asp:View ID=”vwAddCity” runat=”server”>

                                <table>

                                    <tr>

                                        <td>

                                            &nbsp;</td>

                                        <td colspan=”2″>

                                            <asp:ValidationSummary ID=”vsCity” runat=”server”

                                                ValidationGroup=”validateCity” />

                                        </td>

                                        <td style=”width: 49px”>

                                            &nbsp;</td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td style=”width: 316px”>

                                        </td>

                                        <td style=”width: 49px”>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                            CityName:

                                        </td>

                                        <td style=”width: 316px”>

                                            <asp:TextBox ID=”txtCityName” runat=”server” Width=”250px” MaxLength=”50″ ></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvCityName” runat=”server”

                                                ControlToValidate=”txtCityName” ErrorMessage=”City Name is required.”

                                                ValidationGroup=”validateCity”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td style=”width: 49px”>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                            CityCode:

                                        </td>

                                        <td style=”width: 316px”>

                                            <asp:TextBox ID=”txtCityCode” runat=”server” Width=”250px” MaxLength=”3″></asp:TextBox>

                                            <asp:RequiredFieldValidator ID=”rfvCityCode” runat=”server”

                                                ControlToValidate=”txtCityCode” ErrorMessage=”City Code is required”

                                                ValidationGroup=”validateCity”>*</asp:RequiredFieldValidator>

                                        </td>

                                        <td style=”width: 49px”>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                            Country: </td>

                                        <td style=”width: 316px”>

                                            <asp:DropDownList ID=”ddlCityCountry” runat=”server” Width=”250px”>

                                            </asp:DropDownList>

                                        </td>

                                        <td style=”width: 49px”>

                                            </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                            &nbsp;</td>

                                        <td style=”width: 316px”>

                                            <asp:Button ID=”btnSaveCity” runat=”server” onclick=”btnSaveCity_Click”

                                                Text=”Save” ValidationGroup=”validateCity” />

                                            <asp:Button ID=”btnCancelCity” runat=”server” onclick=”btnCancelCity_Click”

                                                Text=”Cancel” />

                                            <asp:Button ID=”btnShowSearchCity” runat=”server”

                                                onclick=”btnShowSearchCity_Click” Text=”Search City” />

                                        </td>

                                        <td style=”width: 49px”>

                                            &nbsp;</td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td style=”width: 316px”>

                                        </td>

                                        <td style=”width: 49px”>

                                        </td>

                                    </tr>

                                </table>

                            </asp:View>

                            <asp:View ID=”vwSearchCity” runat=”server”>

                                <table>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                            Search City:

                                        </td>

                                        <td>

                                            <asp:TextBox ID=”txtSearchCity” runat=”server” ></asp:TextBox>

                                            <asp:Button ID=”btnSearchCity” runat=”server” onclick=”btnSearchCity_Click”

                                                Text=”Search City” />

                                            <asp:Button ID=”btnAddCity” runat=”server” onclick=”btnAddCity_Click”

                                                Text=”Add City” />

                                        </td>

                                        <td>

                                            &nbsp;</td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td colspan=”2″>

                                            <asp:GridView ID=”gvCity” runat=”server” AllowPaging=”True”

                                                AllowSorting=”True” AutoGenerateColumns=”False”

                                                EmptyDataText=”No Records Found”

                                                onpageindexchanging=”gvCity_PageIndexChanging”

                                                onrowcancelingedit=”gvCity_RowCancelingEdit”

                                                onrowdeleting=”gvCity_RowDeleting” onrowediting=”gvCity_RowEditing”

                                                onrowupdating=”gvCity_RowUpdating” onsorting=”gvCity_Sorting”>

                                                <Columns>

                                                    <asp:BoundField DataField=”CityID” HeaderText=”CityID” ReadOnly=”True”

                                                        SortExpression=”CityID” Visible=”False” />

                                                    <asp:TemplateField HeaderText=”City” SortExpression=”CityName”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCityName” runat=”server” Text='<%# Bind(“CityName”) %>’ MaxLength=”50″></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCityName” runat=”server” Text='<%# Bind(“CityName”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridCityName” runat=”server” Text='<%# Bind(“CityName”) %>’ MaxLength=”50″ Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”City Code” SortExpression=”CityCode”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCityCode” runat=”server” Text='<%# Bind(“CityCode”) %>’ MaxLength=”3″></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCityCode” runat=”server” Text='<%# Bind(“CityCode”) %>’></asp:Label>

                                                            <asp:TextBox ID=”txtGridCityCode” runat=”server” Text='<%# Bind(“CityCode”) %>’ MaxLength=”3″ Visible=”false”></asp:TextBox>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Country ID” SortExpression=”CountryID”

                                                        Visible=”False”>

                                                        <EditItemTemplate>

                                                            <asp:TextBox ID=”txtGridCountryID” runat=”server” Text='<%# Eval(“CountryID”) %>’></asp:TextBox>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCountryID” runat=”server” Text='<%# Bind(“CountryID”) %>’></asp:Label>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField HeaderText=”Country” SortExpression=”CountryName”>

                                                        <EditItemTemplate>

                                                            <asp:DropDownList ID=”ddlGridCountryName” runat=”server”  ></asp:DropDownList>

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Label ID=”lblGridCountryName” runat=”server” Text='<%# Bind(“CountryName”) %>’></asp:Label>

                                                            <asp:DropDownList ID=”ddlGridCountryName” runat=”server”  Visible=”false” ></asp:DropDownList>

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField ShowHeader=”False”>

                                                        <EditItemTemplate>

                                                            <asp:Button ID=”btnGridUpdateCity” runat=”server” CausesValidation=”True”

                                                                CommandName=”Update” Text=”Update” />

                                                            &nbsp;<asp:Button ID=”btnGridCancelCity” runat=”server” CausesValidation=”False”

                                                                CommandName=”Cancel” Text=”Cancel” />

                                                        </EditItemTemplate>

                                                        <ItemTemplate>

                                                            <asp:Button ID=”btnGridEditCity” runat=”server” CausesValidation=”False”

                                                                CommandName=”Edit” Text=”Edit” />

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                    <asp:TemplateField ShowHeader=”False”>

                                                        <ItemTemplate>

                                                            <asp:Button ID=”btnGridDeleteCity” runat=”server” CausesValidation=”False”

                                                                CommandName=”Delete” Text=”Delete” />

                                                            <asp:HiddenField ID=”hfCityID” runat=”server” Value='<%# Bind(“CityID”) %>’ />

                                                        </ItemTemplate>

                                                    </asp:TemplateField>

                                                </Columns>

                                            </asp:GridView>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                    <tr>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                        <td>

                                        </td>

                                    </tr>

                                </table>

                            </asp:View>

                        </asp:MultiView>

                    </td>

                    <td>

                    </td>

                </tr>

                <tr>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                    <td>

                    </td>

                </tr>

            </table>           

        </ContentTemplate>

        <Triggers>

        </Triggers>

    </asp:UpdatePanel>

</asp:Content>

Here is the source code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using DAL;

using System.Configuration;

namespace Web{

    public partial class CityPage : System.Web.UI.Page

    {

        #region “Variables”

        Cities city;

        Countries country;

        IOrderedQueryable cityCountry;

        List<Cities> cityList;

        List<Countries> countryList;

        CitiesBLL cityBll;

        CountriesBLL countryBll;

        CitiesCountriesBLL cityCountryBll;

        Entity dbEntity;

        string connString = ConfigurationManager.ConnectionStrings["Entity"].ConnectionString;

        #endregion

        #region “Methods”

        private void MessageBox(string message)

        {

            ScriptManager.RegisterStartupScript(this, this.GetType(), “onclick”, “alert(‘” + message + “‘);”, true);

        }

        private void ResetEntry()

        {

            this.txtCityCode.Text = string.Empty;

            this.txtCityName.Text = string.Empty;

            this.txtSearchCity.Text = string.Empty;

            this.ddlCityCountry.SelectedIndex = -1;

            this.gvCity.DataSource = null;

            this.gvCity.DataBind();

        }

        private void PopulateCountryList()

        {

            try

            {

                countryList = countryBll.RetrieveCountryList();

                this.ddlCityCountry.DataSource = countryList;

                this.ddlCityCountry.DataTextField = “CountryName”;

                this.ddlCityCountry.DataValueField = “CountryID”;

                this.ddlCityCountry.DataBind();

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        private void PopulateGridView()

        {

            try

            {

                cityCountry = cityCountryBll.RetrieveCityCountryByName(this.txtSearchCity.Text.Trim(), Convert.ToString(Session["SortExpression"]), Convert.ToString(Session["SortDirection"]));

                this.gvCity.DataSource = cityCountry;

                this.gvCity.DataBind();

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        private void PopulateGridCountryList(DropDownList countryDDL, string id)

        {

            try

            {

                countryList = countryBll.RetrieveCountryList();

                countryDDL.DataSource = countryList;

                countryDDL.DataTextField = “CountryName”;

                countryDDL.DataValueField = “CountryID”;

                countryDDL.DataBind();

                countryDDL.SelectedValue = id;

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        #endregion

        #region “Events”

        protected void Page_Init(object sender, EventArgs e)

        {

            city = new Cities();

            country = new Countries();

            cityCountry = null;

            cityList = new List<Cities>();

            countryList = new List<Countries>();

            cityBll = new CitiesBLL();

            countryBll = new CountriesBLL();

            cityCountryBll = new CitiesCountriesBLL();

            dbEntity = new Entity(connString);

        }

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!this.Page.IsPostBack)

            {

                PopulateCountryList();

            }

        }

        protected void btnSaveCity_Click(object sender, EventArgs e)

        {

            try

            {

                city = new Cities();

                city.CityCode = this.txtCityCode.Text.Trim();

                city.CityName = this.txtCityName.Text.Trim();

                city.CountryID = Convert.ToInt32(this.ddlCityCountry.SelectedValue);

                if (cityBll.CheckForDuplicateCity(city, false) == false)

                {

                    int result = cityBll.InsertCity(city);

                    if (result > 0)

                        MessageBox(“Successfully add new city, ” + city.CityName);

                    else

                        MessageBox(“Failed to add new city, ” + city.CityName);

                }

                else

                    MessageBox(“Duplicate city name or code, ” + city.CityName);

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        protected void btnCancelCity_Click(object sender, EventArgs e)

        {

            ResetEntry();

        }

        protected void btnShowSearchCity_Click(object sender, EventArgs e)

        {

            this.mvCity.ActiveViewIndex = 1;

        }

        protected void btnSearchCity_Click(object sender, EventArgs e)

        {

            try

            {

                Session["SortDirection"] = “ascending”;

                Session["SortExpression"] = “CityName”;

                PopulateGridView();

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        protected void btnAddCity_Click(object sender, EventArgs e)

        {

            this.mvCity.ActiveViewIndex = 0;

        }

        protected void gvCity_PageIndexChanging(object sender, GridViewPageEventArgs e)

        {

            this.gvCity.PageIndex = e.NewPageIndex;

            PopulateGridView();

        }

        protected void gvCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

        {

            this.gvCity.EditIndex = -1;

            PopulateGridView();

        }

        protected void gvCity_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            try

            {

                HiddenField hf = (HiddenField)this.gvCity.Rows[e.RowIndex].Cells[0].FindControl(“hfCityID”);

                int result = cityBll.DeleteCity(Convert.ToInt32(hf.Value));

                if (result > 0)

                    MessageBox(“Successfully delete this city.”);

                else

                    MessageBox(“Failed to delete this city.”);

                PopulateGridView();

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        protected void gvCity_RowEditing(object sender, GridViewEditEventArgs e)

        {

            try

            {

                this.gvCity.EditIndex = e.NewEditIndex;

                PopulateGridView();

                string countryID = ((TextBox)this.gvCity.Rows[e.NewEditIndex].Cells[3].FindControl(“txtGridCountryID”)).Text;

                DropDownList countryDDL = (DropDownList)this.gvCity.Rows[e.NewEditIndex].Cells[4].FindControl(“ddlGridCountryName”);

                PopulateGridCountryList(countryDDL, countryID);

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        protected void gvCity_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            try

            {

                TextBox name = (TextBox)this.gvCity.Rows[e.RowIndex].Cells[1].FindControl(“txtGridCityName”);

                TextBox code = (TextBox)this.gvCity.Rows[e.RowIndex].Cells[2].FindControl(“txtGridCityCode”);

                DropDownList country = (DropDownList)this.gvCity.Rows[e.RowIndex].Cells[4].FindControl(“ddlGridCountryName”);

                HiddenField hf = (HiddenField)this.gvCity.Rows[e.RowIndex].Cells[6].FindControl(“hfCityID”);

                city.CityCode = code.Text.Trim();

                city.CityID = Convert.ToInt32(hf.Value);

                city.CityName = name.Text.Trim();

                city.CountryID = Convert.ToInt32(country.SelectedValue);

                if (cityBll.CheckForDuplicateCity(city, true) == false)

                {

                    int result = cityBll.UpdateCity(city);

                    if (result > 0)

                        MessageBox(“Successfully update this city, ” + city.CityName);

                    else

                        MessageBox(“Failed to update this city, ” + city.CityName);

                    this.gvCity.EditIndex = -1;

                    PopulateGridView();

                }

                else

                    MessageBox(“Duplicate city Code or name, ” + city.CityName);

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        protected void gvCity_Sorting(object sender, GridViewSortEventArgs e)

        {

            try

            {

                if (Convert.ToString(Session["SortDirection"]) == “ascending”)

                {

                    e.SortDirection = SortDirection.Descending;

                    Session["SortDirection"] = “descending”;

                }

                else

                {

                    e.SortDirection = SortDirection.Ascending;

                    Session["SortDirection"] = “ascending”;

                }

                Session["SortExpression"] = e.SortExpression;

                PopulateGridView();

            }

            catch (System.Exception ex)

            {

                MessageBox(ex.Message + ” ” + ex.StackTrace);

            }

        }

        #endregion

    }

}

Posted in ASP.NET 3.5, ASP.NET 3.5 And C# 3.5, C# 3.5, C# 3.5 and ADO.NET Entity Framework 3.5, Linq to Entity | Leave a comment

How to use comparevalidator to compare date in ASP.NET 3.5?

In designer,

<asp:CompareValidator ID=”cvReturnDate” runat=”server”

                            ControlToValidate=”txtReturnDate”

                            ErrorMessage=”Return date must be valid date.” Type=”Date”

                            ValidationGroup=”validateInquiry” >*</asp:CompareValidator>

In Code,

                    this.cvReturnDate.Operator = ValidationCompareOperator.GreaterThan;

                    this.cvReturnDate.ValueToCompare = DateTime.Now.ToShortDateString();

or you just want to check if it is a date, the use this code instead,

this.cvReturnDate.Operator = ValidationCompareOperator.DataTypeCheck;

Posted in ASP.NET 3.5, ASP.NET 3.5 And C# 3.5, C# 3.5 | Leave a comment

How to display messagebox in asp.net 3.5?

There are many ways to show or display message. I have two ways:

First way is this,

ScriptManager.RegisterStartupScript(this, this.GetType(), “onclick”, “alert(‘” + message + “‘);”, true); 

Second way is this,

String scriptString = “<script language=JavaScript>”;

scriptString += “alert(‘” + message + “‘)”;

scriptString += “</script>”;

this.ClientScript.RegisterStartupScript(this.GetType(), “onlick”, scriptString);

Hope my blog helps you.

Posted in ASP.NET 3.5, ASP.NEt And C# 3.5 And Javascript, C# 3.5, JavaScript | Leave a comment

Migrating old source code of Visual Studio 2010 to Visual Studio 2012

Step 1: Enable nuget restore. Find and click on Project then find and click enable nuget restore.
Step 2: Manage nuget packages and install entityframework and ajaxcontroltoolkit.
Step 3. Download and install ajaxcontroltoolkit 4.5.
Step 4: Click on Toolbox then choose item, browse and find AjaxControlToolkit.dll version 4.5.
Step 5: Add reference to all dll that you need in your project and can be found here, C:\Program Files (x86)\Microsoft Visual Studio 11.0\. For example,
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.WebForms
System.Data.Entity
Step 6: Select a page to set as start page.

Step 7: Replace the following align or valign with vertical and text-align respectively.
Refer to this link, Click Here
Step 8: There are items to change in css 3 from css 1, like cursor:hand to cursor:pointer.
CSS
To align right,
Click Here

Step 9: To deploy or publish the web application. Please refer to the link below,
Reference 1
Reference 2
Reference 3
Reference 4
Reference 5

Step 10: Check for any missing dll. If you cannot find some of them, refer to this link below,
Reference 1

Step 11: To position two column table in the center at the top menu, add this css to menu.css file.
.wrapper
{
position: absolute;
left: 50%;
margin-left: -70px;
}

the idea came from this link,
Align Contents

Step 12: When you wish to insert a image as a background, insert into a css file, this css below,
background: url(../Images/ERRPAGE.png) center no-repeat;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-size: auto auto;

Reference used:
background size
vertical centering

Step 13: If you receive an error message “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”, apply this code before your redirect to error page like this code below,
if (ex.Message.StartsWith("Thread") == false)
{
Session["ErrorMessage"] = ex.Message;
Response.Redirect("~/Forms/Error.aspx", false);
}

Reference used for step 13, Reference used

Step 14: to change the color of the scrollbar of a panel, use the link below,
Bar color
CSS Tutorial
There is no direct way of changing color of scrollbar in a treeview control unless you create new custom treeview control.

Step 15: In case you have this javascript error message “0x800a139e – JavaScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.”, you can insert this meta tag in the master page,
<meta http-equiv="X-UA-Compatible" content="IE=9" />

Step 16: To enable clicking on word displayed to expand the tree. Set the property SelectAction to Expand. To display the treeview in unexpanded format. Set the property Expanded to False.
<asp:TreeNode Text="Transaction" Value="Process" ImageUrl="~/Images/folder.png" Expanded="false" SelectAction="Expand" >

Step 17: To remove the default arrows that appear in the ASP.NET Menu Control. Set the StaticEnableDefaultPopOutImage property to False. This property is responsible for the default arrows that appear in the ASP.NET Menu control. To remove the default arrows that appear in the ASP.NET menu items. Set the DynamicEnableDefaultPopOutImage property to False. This property gets or sets a value indicating whether the built-in image that indicates that a dynamic menu item has a submenu is displayed.

Reference used for step 17:
Reference for DynamicEnableDefaultPopOutImage
Reference for StaticEnableDefaultPopOutImage
Another Reference for StaticEnableDefaultPopOutImage

Step 18: Fixing the displaying of rdlc inside a report viewer 2012 using IIS 7. Please refer to this link to add handler mappings at iis.

Step 19: To display Elmah.axd, allow remote access by setting allowRemoteAccess from false to true at web config file. And add a file extension to allow . Find and click Request Filtering. Find and click Allow file name extension link. Type in .axd at File name extension and then click OK.

Step 20: To insert space between menu and submenu, put some value at DynamicMenuItemStyle-HorizontalPadding  property.
Reference used for step 20

Reference use in migrating from Visual Studio 2010 to Visual Studio 2012
Reference 1
Reference 2
Reference 3
Reference 4
Reference 5
Reference 6

Posted in ASP.NET 4.5, C# 4.5, CSS, HTML 5, Visual Studio 2012 | Leave a comment

Toshiba Service Centers in the Philippines

Tricom Dynamics Inc

Metro House 345 Sen. Gil Puyat Ave, Makati City Manila  1200 Phone: +63 2 890-6525 Fax:+63 2 890-0669 Website: www.tricom.com.ph Email: toshiba.pc.service@tricom.com.ph ServicesPremier Service Provider Notebook Repairs International Warranty Repairs

Tricom Dynamics, IncDoor No. 3, EV Chavez Building Capistrano-Cruz Taal Streets Cagayan De Oro  9000 Phone: +63 8822 733158/733273 Fax:+63 88 855 5388 ServicesNotebook Repairs International Warranty Repairs Premier Service Provider

Tricom Dynamics, IncLevel 2, Machay Building 30 Gorordo Avenue Cebu  6000 Phone: +63 32 232-6385 Fax:+63 32 231-0681 ServicesNotebook Repairs International Warranty Repairs Premier Service Provider

Tricom Dynamics, IncDoor 14 Ebro-Pelayo Building Juan Luna St. Davao City  Phone: +63 822 274137 Fax:+63 822 274147 ServicesNotebook Repairs International Warranty Repairs Premier Service Provider

Servimax Technologies, Inc.Unit G, Gilmore Commercial Plaza 10 Gilmore Avenue New Manila, Quezon City Manila  Phone: +63-2-722-2992 Fax:+63-2-721-9102 ServicesPremier Service Provider Notebook Repairs International Warranty Repairs

Posted in Service Center, Toshiba | Leave a comment