Mike's Blog
13/3/13
IE 7 z-index problems
I was having a bit of trouble on implementing a menu for a web application. Specifically, on IE 7 the applications menu floated beneath the rest of the elements on the page. I googled for the problem, but I couldn't find a comprehensive example to solve my problem. Finally, I found this post which is very helpful, explains why IE reacts the way it does and give a solution with examples. Good work...!
2/10/12
Css for Chrome, Safari and Firefox
Another note to self....
The css I used for a web application seemed to work fine in Firefox 15. Unfortunately, the top:440px did not work as expected. What I did was putting
to solve the problem for Safari and Chrome browsers and within the class I used
\9 refers to IE 9
The css I used for a web application seemed to work fine in Firefox 15. Unfortunately, the top:440px did not work as expected. What I did was putting
@media screen and (-webkit-min-device-pixel-ratio:0) {
div.scroll-home { top: 140px; }
}
to solve the problem for Safari and Chrome browsers and within the class I used
top:140px\9;
\9 refers to IE 9
27/9/12
Step carousel problems
I was messing around with StepCarousel the other day. I tried to use two carousels, both with pagination, in the Web Form. The result was not the desirable!!! When I moused over the images that denote each panel of the first carousel, the images of the second carousel appeared. I got in the javascript that comes with StepCarousel, in the createpaginate method and changed
srcs = [$templateimg.attr('src'), $templateimg.attr('data-over'), $templateimg.attr('data-select')]to
var srcs = [$templateimg.attr('src'), $templateimg.attr('data-over'), $templateimg.attr('data-select')]This resolved my problem and I was happy
18/5/12
Pretty Photo
PrettyPhoto is a jQuery lightBox clone. It is versitile and adds a great look and feel to your project. Unfortunately, documentation for PrettyPhoto is not....well documented :) , leading sometimes to loss of time for a web developer that uses it for the first time. A problem I encountered using PrettyPhoto was that inline content worked fine the events of the buttons where not fired!!! I lost time implementing a pop up only to figure out that I had to develop it in a different way, using the external sites method of implementation. The way i did it was the following...
1.Created a web user control that would act as my pop up
2.Created an aspx page in which I added my web user control
3.In the page I wanted my pop up to appear I added
4.In the document ready fuction I implemented the following
1.Created a web user control that would act as my pop up
2.Created an aspx page in which I added my web user control
3.In the page I wanted my pop up to appear I added
<a id="pretty-photo-opener" href="/Controls/newsLetterPopUp.aspx?iframe=true&width=620&height=470" rel="prettyPhoto"></a>that will act as the element that will open the pop up
4.In the document ready fuction I implemented the following
<script type="text/javascript">5.Finally, in the my web user control I implemented the following code to close the PrettyPhoto pop up, since I used a custom close button and not the one of the PrettyPhoto
$(document).ready(function() {
$("a[rel^='prettyPhoto']").prettyPhoto({ theme: '', callback: function() { } });
$('#pretty-photo-opener').trigger('click');
}
});
</script>
<script type="text/javascript">For more information about PrettyPhoto check this
function closeBox() {
window.parent.$.prettyPhoto.close();
}
</script>
14/5/12
Forms Authentication for a specific folder of your project
I post this mostly as a reminder to myself, just in case I need it again.
Today, one of the project's requirements was to deny access to unauthenticated user, in a specific folder of the web application. This folder contained reports generated by an SQL query, so general users should not be able to view them. The solution to the problem consisted of the following steps.
Create a new folder in the solution of my project and within it create a page that would host the reports and a custom login page.
In the Web config file of my project I added the following tag sections
in which I specify that this folder will deny access to unathendicated users and
in which I specify that for this folder I will be using Forms authentication, in such a way that if am unauthenticated user tries to access the report page, he/she will be redirected to the custom login page and after a successfull login he/she will be redirected to the REPORT PAGE automatically.
Finally, in the code behind file of my LOGIN PAGE, in the login button click event I added the following code to use the Forms authentication method.
In conclusion, I could probably use a session object to store the authenticated user's credentials and check if the session is null or not in the page load event of the REPORT PAGE. In contrast, I was able to achieve the same result using Forms authentication, with less coding, which is always better... :)
Today, one of the project's requirements was to deny access to unauthenticated user, in a specific folder of the web application. This folder contained reports generated by an SQL query, so general users should not be able to view them. The solution to the problem consisted of the following steps.
Create a new folder in the solution of my project and within it create a page that would host the reports and a custom login page.
In the Web config file of my project I added the following tag sections
<location path="FOLDER NAME">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
in which I specify that this folder will deny access to unathendicated users and
<authentication mode="Forms">
<forms name="login" loginUrl="FOLDER NAME/lLOGIN PAGE.aspx" defaultUrl="REPORT PAGE.aspx" protection="All" path="/" timeout="30" />
</authentication>
in which I specify that for this folder I will be using Forms authentication, in such a way that if am unauthenticated user tries to access the report page, he/she will be redirected to the custom login page and after a successfull login he/she will be redirected to the REPORT PAGE automatically.
Finally, in the code behind file of my LOGIN PAGE, in the login button click event I added the following code to use the Forms authentication method.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.ContentId.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, "");
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
Response.Redirect(Request.RawUrl);
In conclusion, I could probably use a session object to store the authenticated user's credentials and check if the session is null or not in the page load event of the REPORT PAGE. In contrast, I was able to achieve the same result using Forms authentication, with less coding, which is always better... :)
18/9/10
Sample C#, .NET Framework 3.5 project
I always want to provide possible employers with a sample of my work. I decided to implement a Web Application in C# along with .NET Framework 3.5 in order for employers to get a grasp on whether I am suitable for the job. The project is called NewCertification and it is all about data retrieval and manipulation on the MS SQL Database, by communicating with it using an asmx Web Service
· MasterPages
· WebServices
· ADO.NET
· AJAX
· User roles
· Localization
· Exception Handling/Logging
· Authorization/Authentication
· C# object oriented programming
· Stored Procedures
· Cryptography
· Configuration Files
· CSS Files
· Encrypted Passwords in Database
Logging in the Web Application
1. LoginUser.aspx
a. The user enters a username and password
b. Online Certification makes a Web Service call to validate the credentials and returns a Dataset
c. If the Dataset contains no rows, the System alerts that there is no such user
d. If the Dataset contains more than one row, this means that the user is joined to more than one role. Note that due to the implementation on newUser.aspx, the usernames are unique. The system redirects the user to userRoles.aspx to choose the desired role and continue to the specific homepage.
e. If the Dataset contains a single row, redirect the user to his/hers homepage according to his/hers role
Authorization/Authentication
All WebContentForms use pageBase as their MasterPage. In the page load event of pageBase, the system checks if the Session userPk, username etc are set which can only be done with proper logging in. If these are not set Online Certification redirects the user to loginAgain.aspx, prompting for logging in. Thus if someone tries to bypass the log in page, by changing the text of the address bar to newUser.aspx for example, he/she will not be able to.
Exception Logging
Just like every system, Online Certification, will face exceptions. In order to provide better and faster support for the users, every exception will be logged in the Database. In the case of an exception, the user will be redirected to the exception page where he/she will receive the exception pk. After that he/she will be able to contact the system developers and provide them the pk, which will help them better understand what went wrong by querying the Database for the StackTrace and Message that corresponds to the specific pk.
Visit this for some code implemented for the NewCertification project
Find the whole project, along with the Database and its log file in mdf format here
You will probably have to change the connection string in the WebService Web Config file to make a successful connection to the DatabaseTechnologies/Techniques used
· MasterPages
· WebServices
· ADO.NET
· AJAX
· User roles
· Localization
· Exception Handling/Logging
· Authorization/Authentication
· C# object oriented programming
· Stored Procedures
· Cryptography
· Configuration Files
· CSS Files
· Encrypted Passwords in Database
Logging in the Web Application
1. LoginUser.aspx
a. The user enters a username and password
b. Online Certification makes a Web Service call to validate the credentials and returns a Dataset
c. If the Dataset contains no rows, the System alerts that there is no such user
d. If the Dataset contains more than one row, this means that the user is joined to more than one role. Note that due to the implementation on newUser.aspx, the usernames are unique. The system redirects the user to userRoles.aspx to choose the desired role and continue to the specific homepage.
e. If the Dataset contains a single row, redirect the user to his/hers homepage according to his/hers role
Authorization/Authentication
All WebContentForms use pageBase as their MasterPage. In the page load event of pageBase, the system checks if the Session userPk, username etc are set which can only be done with proper logging in. If these are not set Online Certification redirects the user to loginAgain.aspx, prompting for logging in. Thus if someone tries to bypass the log in page, by changing the text of the address bar to newUser.aspx for example, he/she will not be able to.
Exception Logging
Just like every system, Online Certification, will face exceptions. In order to provide better and faster support for the users, every exception will be logged in the Database. In the case of an exception, the user will be redirected to the exception page where he/she will receive the exception pk. After that he/she will be able to contact the system developers and provide them the pk, which will help them better understand what went wrong by querying the Database for the StackTrace and Message that corresponds to the specific pk.
1/9/10
Sample C#, Silverlight 4, WCF RIA Service Project
This project is based on the idea presented by Ian Griffiths on MSDN's Channel 9 videos series Hand On Lab Silverlight 4. Ian presented a Business Application, where users can log in and attend events. Unfortunately the project he ended up presenting is not so "Business" like. Ian spends a lot of time on out of browser techniques, Web Cams and Drag & Drop and only 7 minutes on user Authentication.
Another bad thing about his presentation, is that he only presented selecting and updating single entities in the database and not pivot tables, such as users_roles for example, which would be the case of a normalized, business database.
The project I ended up building, is not a business application, but a navigation application. I aim to incorporate user log in, user roles and authentication when Pro Business Application with Silverlight 4 gets shipped from Amazon.
In this project I explore the capabilities of the Entity Framework, Domain Service classes and WCF RIA Services.
Find the project here
I used customization of the Domain Service class produced by VS 2010:
To overcome the problem of feeding my DataGrids with pivot tables, I used SQL Views to represent the data
The overall experience was good, although I had problems which included my Entities losing their last characters when trying to generate the ADO.NET Entity Data Model. My entity Users became User and clashed with the built in class User. I also lost Intellisence in the XAML editor when I dragged and dropped a Wrap Panel, not to mention somehow the breakpoints stopped getting hit!!!
I really hope Pro Business Application with Silverlight 4 book meets my expectations, since I haven't found anything yet talking about real Business Apps.
Another bad thing about his presentation, is that he only presented selecting and updating single entities in the database and not pivot tables, such as users_roles for example, which would be the case of a normalized, business database.
The project I ended up building, is not a business application, but a navigation application. I aim to incorporate user log in, user roles and authentication when Pro Business Application with Silverlight 4 gets shipped from Amazon.
In this project I explore the capabilities of the Entity Framework, Domain Service classes and WCF RIA Services.
Find the project here
I used customization of the Domain Service class produced by VS 2010:
[Query(IsComposable = false)]
public Attendee GetAttendee(string name, string surname, string email)
{
return this.ObjectContext.Attendees.SingleOrDefault(a => (a.name == name) && (a.surname == surname) && (a.email == email));
}
[Query(IsComposable = false)]and also the DomainDataSource provided by RIA Services
public Event_Centers GetEventCenter(int centerPk)
{
return this.ObjectContext.Event_Centers.SingleOrDefault(c => c.pk == centerPk);
}
<riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance my:MyEventsCourses, CreateList=true}" Height="0" LoadedData="myEventsCoursesDomainDataSource_LoadedData" Name="myEventsCoursesDomainDataSource" QueryName="GetMyEventsCoursesQuery" Width="0">
<riaControls:DomainDataSource.DomainContext>
<my1:EventPlannerDomainContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
int selectedEvent = Convert.ToInt32(NavigationContext.QueryString["eventId"]);in order to represent the database entities on the UI, either in DataGrids or in Details view, as provided by VS 2010.
myEventsCoursesDomainDataSource.FilterDescriptors.Add(new FilterDescriptor { Operator = FilterOperator.IsEqualTo, PropertyPath = "pk", Value = selectedEvent });
To overcome the problem of feeding my DataGrids with pivot tables, I used SQL Views to represent the data
The overall experience was good, although I had problems which included my Entities losing their last characters when trying to generate the ADO.NET Entity Data Model. My entity Users became User and clashed with the built in class User. I also lost Intellisence in the XAML editor when I dragged and dropped a Wrap Panel, not to mention somehow the breakpoints stopped getting hit!!!
I really hope Pro Business Application with Silverlight 4 book meets my expectations, since I haven't found anything yet talking about real Business Apps.
31/8/10
Sample C#, Silverlight 4, WCF project
This project is called The Gardener. It is a C#, .NET, Silverlight application which connects to an MS SQL Server 2008 via WCF Services.
The project in based on the ideas and techniques used in Pro Silverlight 3 in C# and Microsoft Silverlight 4 Business Application Development Beginners Guide books, which provide a great way on getting to know Silverlight 3 and 4 and develop a small scale business application
Find the whole code along with its Database and log file in .mdf format here
The Gardener was built using:
- MS Visual Studio 2010
- MS SQL Server 2008
- Expression Blend 3
- Silverlight 4
- WCF Services
- Pages and Frames for navigation
- Animations
- Animation Easing
- Bing Maps
- InkPresenter
- UriMapping
- Silverlight themes
The Gardener makes use of asynchronous WCF Service calls to store sketches that users make in the Database, by converting the Strokes Collection of the InkPresenter into XML format. Users can after that talk about their dream garden with the people of the Gardener.
The Gardener also uses Bing Maps to pin point the location of the stores upon the map. Bing Maps is the only map control that incorporates fully with Silverlight, as mentioned in Microsoft Silverlight 4 Business Application Development Beginners Guide. Note that you must make an account in Bing Maps and get a key which you must incorporate in the Map control, in your XAML, to get rid of that annoying alert on the Bing Map, which informs you that you provided invalid credentials.
In the Products section, I made use of the Silverlight DataGrid. I must say that this control not only looks great without any customization but it is also very powerful. Sorting, column resizing/moving and field editing with no or with very little code, unlike the ASP.NET GridView.
I used Pages and Frames for navigation in this project, since in this way I can keep track of the browser's history and navigate using the backwards and forward buttons of the browsers.
Animations and Animation Easing gives a better look and feel on the Pages of the application and makes it even better in the eyes of the customers.
Finally, my overall experience using the tools, technologies, techniques and IDEs was great, although I had a little bit of a hard time installing MS SQL Server 2008 and MS Visual Studio on my Windows 7 machine.
Next project I am looking forward to implementing is a full scale business Silverlight 4 application, using the Silverlight business application template of MS Visual Studio 2010 which will connect to the Database using RIA Services. For that I intend to study from Pro Business Applications with Silverlight 4 by Chris Anderson.
The project in based on the ideas and techniques used in Pro Silverlight 3 in C# and Microsoft Silverlight 4 Business Application Development Beginners Guide books, which provide a great way on getting to know Silverlight 3 and 4 and develop a small scale business application
Find the whole code along with its Database and log file in .mdf format here
The Gardener was built using:
- MS Visual Studio 2010
- MS SQL Server 2008
- Expression Blend 3
- Silverlight 4
- WCF Services
- Pages and Frames for navigation
- Animations
- Animation Easing
- Bing Maps
- InkPresenter
- UriMapping
- Silverlight themes
The Gardener makes use of asynchronous WCF Service calls to store sketches that users make in the Database, by converting the Strokes Collection of the InkPresenter into XML format. Users can after that talk about their dream garden with the people of the Gardener.
The Gardener also uses Bing Maps to pin point the location of the stores upon the map. Bing Maps is the only map control that incorporates fully with Silverlight, as mentioned in Microsoft Silverlight 4 Business Application Development Beginners Guide. Note that you must make an account in Bing Maps and get a key which you must incorporate in the Map control, in your XAML, to get rid of that annoying alert on the Bing Map, which informs you that you provided invalid credentials.
In the Products section, I made use of the Silverlight DataGrid. I must say that this control not only looks great without any customization but it is also very powerful. Sorting, column resizing/moving and field editing with no or with very little code, unlike the ASP.NET GridView.
I used Pages and Frames for navigation in this project, since in this way I can keep track of the browser's history and navigate using the backwards and forward buttons of the browsers.
Animations and Animation Easing gives a better look and feel on the Pages of the application and makes it even better in the eyes of the customers.
Finally, my overall experience using the tools, technologies, techniques and IDEs was great, although I had a little bit of a hard time installing MS SQL Server 2008 and MS Visual Studio on my Windows 7 machine.
Next project I am looking forward to implementing is a full scale business Silverlight 4 application, using the Silverlight business application template of MS Visual Studio 2010 which will connect to the Database using RIA Services. For that I intend to study from Pro Business Applications with Silverlight 4 by Chris Anderson.
25/8/10
Sample C#, .NET Framework 3.5 project
I always want to provide possible employers with a sample of my work. I decided to write a Web Application in C# along with .NET Framework 3.5 in order for employers to get a grasp on whether I am suitable for the job. The project is called NewCertification and it is all about data retrieval and manipulation on the MS SQL Database, by communicating with it using an asmx Web Service
· MasterPages
· WebServices
· ADO.NET
· AJAX
· User roles
· Localization
· Exception Handling/Logging
· Authorization/Authentication
· C# object oriented programming
· Stored Procedures
· Cryptography
· Configuration Files
· CSS Files
· Encrypted Passwords in Database
Logging in the Web Application
1. LoginUser.aspx
a. The user enters a username and password
b. Online Certification makes a Web Service call to validate the credentials and returns a Dataset
c. If the Dataset contains no rows, the System alerts that there is no such user
d. If the Dataset contains more than one row, this means that the user is joined to more than one role. Note that due to the implementation on newUser.aspx, the usernames are unique. The system redirects the user to userRoles.aspx to choose the desired role and continue to the specific homepage.
e. If the Dataset contains a single row, redirect the user to his/hers homepage according to his/hers role
Authorization/Authentication
All WebContentForms use pageBase as their MasterPage. In the page load event of pageBase, the system checks if the Session userPk, username etc are set which can only be done with proper logging in. If these are not set Online Certification redirects the user to loginAgain.aspx, prompting for logging in. Thus if someone tries to bypass the log in page, by changing the text of the address bar to newUser.aspx for example, he/she will not be able to.
Exception Logging
Just like every system, Online Certification, will face exceptions. In order to provide better and faster support for the users, every exception will be logged in the Database. In the case of an exception, the user will be redirected to the exception page where he/she will receive the exception pk. After that he/she will be able to contact the system developers and provide them the pk, which will help them better understand what went wrong by querying the Database for the StackTrace and Message that corresponds to the specific pk.
Visit this for some code implemented for the NewCertification project
Find the whole project, along with the Database and its log file in mdf format here
You will probably have to change the connection string in the WebService Web Config file to make a successful connection to the DatabaseTechnologies/Techniques used
· MasterPages
· WebServices
· ADO.NET
· AJAX
· User roles
· Localization
· Exception Handling/Logging
· Authorization/Authentication
· C# object oriented programming
· Stored Procedures
· Cryptography
· Configuration Files
· CSS Files
· Encrypted Passwords in Database
Logging in the Web Application
1. LoginUser.aspx
a. The user enters a username and password
b. Online Certification makes a Web Service call to validate the credentials and returns a Dataset
c. If the Dataset contains no rows, the System alerts that there is no such user
d. If the Dataset contains more than one row, this means that the user is joined to more than one role. Note that due to the implementation on newUser.aspx, the usernames are unique. The system redirects the user to userRoles.aspx to choose the desired role and continue to the specific homepage.
e. If the Dataset contains a single row, redirect the user to his/hers homepage according to his/hers role
Authorization/Authentication
All WebContentForms use pageBase as their MasterPage. In the page load event of pageBase, the system checks if the Session userPk, username etc are set which can only be done with proper logging in. If these are not set Online Certification redirects the user to loginAgain.aspx, prompting for logging in. Thus if someone tries to bypass the log in page, by changing the text of the address bar to newUser.aspx for example, he/she will not be able to.
Exception Logging
Just like every system, Online Certification, will face exceptions. In order to provide better and faster support for the users, every exception will be logged in the Database. In the case of an exception, the user will be redirected to the exception page where he/she will receive the exception pk. After that he/she will be able to contact the system developers and provide them the pk, which will help them better understand what went wrong by querying the Database for the StackTrace and Message that corresponds to the specific pk.
22/7/10
JavaSript to get query string items
I wanted to make my own function in order to get the query string items. The code below initializes an array which will contain queryStringItem objects, with properties name and value. So if the text in the address bar is
The code was tested in Internet Explorer 8.0.7600 and Mozilla FireFox 3.5.10
http://www.blogger.com/post-create.g?blogID=6495603084419766846the code will return an array of length 1, which will store an object of type queryStringItem whose name property will be equal to blogID and value property equal to 6495603084419766846.
The code was tested in Internet Explorer 8.0.7600 and Mozilla FireFox 3.5.10
function getQueryStringItemArray() {
//Check if there is a query string
if (location.search.length > 0) {
//Initialize the Array which will store the queryStringItem Objects
var queryArray = new Array();
//Get the query string and ommit the ? charqacter
var queryString = location.search.replace("?", "");
//Devide the query string into its components (name = value) and store them all in an Array
//so that each Array slot contains a name = value string
var queryStringItems = queryString.split("&");
//Create the queryStringObject for every name = value string created above
//Push every queryStringObject into the queryArray, so that each slot contains a
//queryStringObject with properties name and value
for (var indexOfQueryStringItems = 0; indexOfQueryStringItems < queryStringItems.length; indexOfQueryStringItems++) {
queryArray.push(createQueryStringItem(queryStringItems[indexOfQueryStringItems]));
}
}
return queryArray;
}
function createQueryStringItem(someString) {
var queryStringItem = new Object();
var queryStringItemParts = someString.split("=");
queryStringItem.name = decodeURIComponent(queryStringItemParts[0]);
queryStringItem.value = decodeURIComponent(queryStringItemParts[1]);
return queryStringItem;
}
21/2/10
Developing Silverlight 3.0 Web Applications
Developing a Silverlight Web application is a great experience. To get started all you need is Visual Studio 2008 with Service Pack 1 installed, Silverlight 3.0 SDK, Silverlight toolkit and Expression Blend 3.0. Expression Blend is needed since Visual Studio 2008 does not have a designer so you will not be able to drag and drop controls like you do in aspx pages. Blend will give you an easy solution to apply positioning etc on your controls, unless you want to do it by configuring the XAML file!!! Anyway Visual Studio 2010 release will have a designer so just be patient...
Download the tools at http://silverlight.net/getstarted/
Building your first Silverlight Web Application will not be difficult if you are already familiar with XML, since everything that has to do with designing and configuring your pages is done by writing on a XAML file.
If you are unfamiliar with XAML visit http://msdn.microsoft.com/en-us/library/ms752059.aspx
Building the back bone of a Silverlight Web Application, Visual Studio 2008 gives you the option to create a stand alone Silverlight Application or a solution that contains a Silverlight Application project and a project with the nessecary aspx pages in order to test your application.
When deploying a Silverlight Web Application keep in mind that not everyone has Silverlight installed on their machines. This means that the end user will be prompted by default to install Silverlight in order to proceed. But not every user is "Computer Friendly", meaning that my father for example will hesitate to install the new technology fearing that Silverlight might be a virus or that malicious code will destroy his computer.
Quoting a tip in Matthew MacDonald's Pro Silverlight 3 in C#
A final issue is that of the versioning. Silverlight 4 Beta is already out there. So what will happen if I have Silverlight 3 and try to view a site on Silverlight 4???Again Silverlight will show a dialog box prompting for upgrades etc something that a non "Computer Friendly" person might be suspicious of. The suggestion is to make the upgrade part of your Web Application by customizing its behavior when the version problem occurs.
More on Silverlight about to come...
Download the tools at http://silverlight.net/getstarted/
Building your first Silverlight Web Application will not be difficult if you are already familiar with XML, since everything that has to do with designing and configuring your pages is done by writing on a XAML file.
If you are unfamiliar with XAML visit http://msdn.microsoft.com/en-us/library/ms752059.aspx
Building the back bone of a Silverlight Web Application, Visual Studio 2008 gives you the option to create a stand alone Silverlight Application or a solution that contains a Silverlight Application project and a project with the nessecary aspx pages in order to test your application.
When deploying a Silverlight Web Application keep in mind that not everyone has Silverlight installed on their machines. This means that the end user will be prompted by default to install Silverlight in order to proceed. But not every user is "Computer Friendly", meaning that my father for example will hesitate to install the new technology fearing that Silverlight might be a virus or that malicious code will destroy his computer.
Quoting a tip in Matthew MacDonald's Pro Silverlight 3 in C#
Studies show that Web Surfers are far more likely to make it through an installation process on the Web if they are guided to do it as a part of an application, rather than prompted to install it as a technology...This means that users might be suspicious of the Silverlight logo, small banner and the Get Silverlight button that appears on their screen of they do not have Silvelight and try to view your page. To give web surfers a friendlier experience try to customize that content and make it part of your Web Application
A final issue is that of the versioning. Silverlight 4 Beta is already out there. So what will happen if I have Silverlight 3 and try to view a site on Silverlight 4???Again Silverlight will show a dialog box prompting for upgrades etc something that a non "Computer Friendly" person might be suspicious of. The suggestion is to make the upgrade part of your Web Application by customizing its behavior when the version problem occurs.
More on Silverlight about to come...
7/2/10
How to create a web custom control
The way I went about it was to add a class library to my Web Application. After that I made my class eg customGrid inherit from GridView. On the Solution Configuration I changed the setting from Debug to Release in order to get the DLL from the release folder and add the newly built control to my toolbox...
I dragged and dropped the control on my Default.aspx and went on to built the whole prject on debug mode. That's when I got the Warning
Another way to go around it is to open IIS and
I dragged and dropped the control on my Default.aspx and went on to built the whole prject on debug mode. That's when I got the Warning
Warning 1 Generation of designer file failed: Unknown server tag 'cc1:customGrid1'. C:\Users\MSen\Documents\Visual Studio 2008\Projects\myGridTest2\myGridTest2\Default.aspx 16 0 myGridTest2This warning makes one unable to access the properties and methods of the new control, trying to set its DataSourse for example, since the Default.aspx.designer.cs does not contain code for our control. Thus the way to go around this warning and become able to access the members of the control is to modify the Default.aspx.designer.cs by including the highlighted code
public partial class _Default {The afore mentioned work around will make you able to access te members of the control, but the warning will still appear every time you built the project
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::customControlNamespace.CustomControlName CustomControlID;
}
Another way to go around it is to open IIS and
1) Go to 'Default Web Site' properties.If IIS is not visible try
2) At 'Web Site' Tab click on 'Advanced..' button.
3) In 'Multiple identities for this site' list select '80:localhost' row and then click 'Edit' button.
4) Erase the 'localhost' string there and click ok.
5) Now close your solution in Visual Studio and open it again.
Opening Control Panel, Programs & Features, Turn Windows Features on or off, Internet Information Services and choose the IIS Management Console
10/12/09
Wrapper class for Database connectivity and query execution
Have you ever tried to to wrap up code when dealing with DataSets, SqlDataAdapters, SqlConnections and SqlTransactions??? It can be really tricky sometimes.
You can download the wrapper class here
It comes along with a test project, to check whether it meets your requirements. Make sure you change the Connection String in the app.config to point to your Database
Prortion of the wrapper class, concerning DataSets, can be seen below
You can download the wrapper class here
It comes along with a test project, to check whether it meets your requirements. Make sure you change the Connection String in the app.config to point to your Database
<?xml version="1.0" encoding="utf-8" ?>Also change the Application.Run(FORM TO RUN) to check out the corresponding form and method calls of the wrapper class
<configuration>
<connectionStrings>
<add name="cnString" connectionString="YOUR CONNECTION STRING HERE" />
</connectionStrings>
</configuration>
/// <summary>
/// The main entry point for the application.
/// In Application.Run(new executeNonQuery_handle()) enter Command_Handle, //Connection_handle, //DataSet_handle, executeNonQuery_handle,
/// Parameter_handle, SqlDataReader_handle to check out the corresponding form
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DataSet_handle());
}
Prortion of the wrapper class, concerning DataSets, can be seen below
public static DataSet getDataSet(string commandText, CommandType commandType, SqlConnection connection, int isCaseSensitive, string dataSetName, int enforceConstraints, params SqlParameter[] sqlParameters)
{
DataSet ds = null;
SqlDataAdapter ad = null;
try
{
ad = new SqlDataAdapter();
ad.SelectCommand = getSqlCommand(commandText,commandType, sqlParameters);
if (connection != null)
{
ad.SelectCommand.Connection = connection;
}
else
{
ad.SelectCommand.Connection = getConnection();
}
ds = new DataSet();
if (isCaseSensitive != -1)
{
ds.CaseSensitive = Convert.ToBoolean(isCaseSensitive);
}
if (!dataSetName.Equals(string.Empty))
{
ds.DataSetName = dataSetName;
}
if (enforceConstraints != -1)
{
ds.EnforceConstraints = Convert.ToBoolean(enforceConstraints);
}
ad.Fill(ds);
}
catch(Exception ex)
{
throw ex;
}
finally
{
ad.Dispose();
}
return ds;
}
public static DataSet getDataSet(string commandText, params SqlParameter[] sqlParameters)
{
return getDataSet(commandText, CommandType.StoredProcedure, null, -1, string.Empty, -1, sqlParameters);
}
public static DataSet getDataSet(SqlCommand command, CommandType commandType, SqlConnection connection, int isCaseSensitive, string dataSetName, int enforceConstraints, params SqlParameter[] sqlParameters)
{
DataSet ds = null;
SqlDataAdapter ad = null;
try
{
ad = new SqlDataAdapter(command);
ad.SelectCommand.CommandType = commandType;
if (connection != null)
{
ad.SelectCommand.Connection = connection;
}
else
{
ad.SelectCommand.Connection = getConnection();
}
foreach (SqlParameter _param in sqlParameters)
{
ad.SelectCommand.Parameters.Add(_param);
}
ds = new DataSet();
if (isCaseSensitive != -1)
{
ds.CaseSensitive = Convert.ToBoolean(isCaseSensitive);
}
if (dataSetName != string.Empty)
{
ds.DataSetName = dataSetName;
}
if (enforceConstraints != -1)
{
ds.EnforceConstraints = Convert.ToBoolean(enforceConstraints);
}
ad.Fill(ds);
}
//The value parameter is null
catch (ArgumentNullException ex)
{
throw ex;
}
//The SqlParameter specified in the value parameter is already added to this or another SqlParameterCollection
catch (ArgumentException ex)
{
throw ex;
}
//The parameter passed was not a SqlParameter
catch (InvalidCastException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
ad.Dispose();
}
return ds;
}
public static DataSet getDataSet(SqlCommand command, params SqlParameter[] sqlParameters)
{
return getDataSet(command, CommandType.StoredProcedure, null, -1, string.Empty, -1, sqlParameters);
}
21/11/09
What to avoid while programming
Here are some things to avoid doing when programming
1. Hard coded connection strings. They make the maintenance of the code very difficult. Instead one should use web.config in the case of Web Sites or app.config in the case of Windows Forms
2.Hard codded SQL Statement. They can easily lead to SQL Injection, a practice used by intruders, to gain access to the projects database
3.Bad or no Exception Handling. It is obvious how this can lead to problems
4.No Exception Loging. It is very common, when a project first gets deployed, even if it has undergone repetative testing, that it will have some bugs that will lead to Exceptions. In the catch clause of your Exception Handling implement code to store the Exceptions message, stack trace and if possible the user_fk of the user that caused that Exception, in the database or to a log file.
5.No Disposing of objects that are no longer needed. All object that implement the IDisposable interface can be disposed. If a custom object implements the IDisposable interface you can implement your own Dispose method
6.No Garbage Collecting. If possible and when needed call the Garbage Collector for automatic memory management
7.No classes to represent bussiness logic. Implement wrapper classes to connect to your database and execute stored procedures. Do not have SqlAdapters, DataSet and SqlCommand object all over your aspx.cs file
8.Make use of the Disconnected model instead of the Connected model when connecting to the database for performance reasons. This means using DataSets insted of SqlDataReaders
9.Do not use temporary tables, cursors, retriaval of unessesary database fields, or making use of unessesary order bys when programming your stored procedures for performance reasons
1. Hard coded connection strings. They make the maintenance of the code very difficult. Instead one should use web.config in the case of Web Sites or app.config in the case of Windows Forms
2.Hard codded SQL Statement. They can easily lead to SQL Injection, a practice used by intruders, to gain access to the projects database
3.Bad or no Exception Handling. It is obvious how this can lead to problems
4.No Exception Loging. It is very common, when a project first gets deployed, even if it has undergone repetative testing, that it will have some bugs that will lead to Exceptions. In the catch clause of your Exception Handling implement code to store the Exceptions message, stack trace and if possible the user_fk of the user that caused that Exception, in the database or to a log file.
5.No Disposing of objects that are no longer needed. All object that implement the IDisposable interface can be disposed. If a custom object implements the IDisposable interface you can implement your own Dispose method
6.No Garbage Collecting. If possible and when needed call the Garbage Collector for automatic memory management
7.No classes to represent bussiness logic. Implement wrapper classes to connect to your database and execute stored procedures. Do not have SqlAdapters, DataSet and SqlCommand object all over your aspx.cs file
8.Make use of the Disconnected model instead of the Connected model when connecting to the database for performance reasons. This means using DataSets insted of SqlDataReaders
9.Do not use temporary tables, cursors, retriaval of unessesary database fields, or making use of unessesary order bys when programming your stored procedures for performance reasons
20/11/09
Ajax AutoComplete
Ajax provides a cool way to implement the AutoComplete feature on TextBoxes. AutoComplete is a very useful feature for Web Sites, plus it makes your final product more dynamic in the eyes of the end user and more expensive in the eyes of your client and to top all of that it is very easy to implement.
What you will need is an aspx file and a Web Service
1.In the WebForm that you wish to implement the AutoComplete TextBox, drag & drop a ScriptManager, found under AJAX Extensions and a TextBox
2.Place your mouse over the TextBox and add the AutoCompleteExtender to your TextBox
3.Add a WebService to your solution. The method you must use must have the following signature
5. Finally, your aspx must look like this
Have fun!!!
What you will need is an aspx file and a Web Service
1.In the WebForm that you wish to implement the AutoComplete TextBox, drag & drop a ScriptManager, found under AJAX Extensions and a TextBox
2.Place your mouse over the TextBox and add the AutoCompleteExtender to your TextBox
3.Add a WebService to your solution. The method you must use must have the following signature
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] HelloWorld(string prefixText, int count)
//Make sure that you uncomment the line
//just after the using statements
[System.Web.Script.Services.ScriptService]
4.Your WebService method must look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
//InitializeComponent();
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] HelloWorld(string prefixText, int count)
{
//Your connectionString will surely be different than mine
SqlConnection conne = new SqlConnection(@"Data Source=MSEN-PC\SQLEXPRESS;Initial Catalog=BookStore;Integrated Security=True");
//Since probably your database will be different too, select the appropriate field from your db table to appear in the AutoComplete
SqlDataAdapter ad = new SqlDataAdapter("select name from book where name like '" + prefixText + "%'", conne);
DataSet ds = new DataSet();
ad.Fill(ds);
Listlist = new List ();
count = 0;
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(ds.Tables[0].Rows[count]["name"].ToString());
count++;
}
return list.ToArray();
}
}
5. Finally, your aspx must look like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<!--Make sure you add the Services tag within ScriptManager-->
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender
ID="TextBox1_AutoCompleteExtender"
runat="server"
DelimiterCharacters=""
Enabled="True"
<!-The name of the WebService to use-->
ServicePath="WebService.asmx"
<!-The name of the WebMethod to use-->
ServiceMethod="HelloWorld"
TargetControlID="TextBox1"
<!-The minimum characters before AutoComplete starts-->
MinimumPrefixLength="1">
</cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
Have fun!!!
15/11/09
Hack_This_Site
No! I don't encourage you to hack this site as you might think!!!
HackThisSite is a training ground for hackers and generally people who wish your site crashes, want to steal important information or cause denial of service to a system. I know, I know...many of you mid-level and senior programmers already are familiar with the threat that SQL injection posses to a system, but an entry level programmer might learn something on security studying this site...
The site includes missions that you must complete and in each level the mission becomes harder. And who knows...maybe a student might find a site that uses hardcoded sql statements instead of stored procedures or JAVA prepared statements!!!
Good luck, be white hat!!!
HackThisSite is a training ground for hackers and generally people who wish your site crashes, want to steal important information or cause denial of service to a system. I know, I know...many of you mid-level and senior programmers already are familiar with the threat that SQL injection posses to a system, but an entry level programmer might learn something on security studying this site...
The site includes missions that you must complete and in each level the mission becomes harder. And who knows...maybe a student might find a site that uses hardcoded sql statements instead of stored procedures or JAVA prepared statements!!!
Good luck, be white hat!!!
Εγγραφή σε:
Αναρτήσεις (Atom)