- It breaks dependencies between classes and promote loose coupling.
- IoC is about programming to interface, if A uses B, then you can create an interface I that B implements and then let A uses an instance of I.
- Dependency Injection & Service Locator are two ways of implementing IoC.
- Dependency Injection
- Constructor injection: Constructor Injection is the DI technique of passing an object's dependencies to its constructor.
- Property injection
- IoC is vital for doing Test Driven Development. To be able to unit test your ASP.NET application, we will need to loose couple the business logic layer and data access layer, a mock object can be used. A mock object simulates the responses of an actual object, acting as if it's using a real resource. They're great for mocking access to a database, mocking calls to IO, mocking calls to a web service, etc.
Thursday, January 13, 2011
Inversion of Control
Friday, March 5, 2010
ASP.NET Caching
- Page Output Caching
- Partial Page Caching
- DataSource Caching
- Data Caching
- When using the cache, it is important to understand that items that you add to the cache might not be there when you attempt to retrieve the item in the future. The cache supports scavenging. When memory resources become low, items are automatically evicted from the cache.
- When you add an item to the Cache, you can specify a particular priority for the item. Specifying a priority provides you with some control over when an item gets evicted from the Cache.
- You can add almost any object to the cache. For example, you can add custom components, DataSets, DataTables, ArrayLists, and Lists to the cache.
- You shouldn’t add items to the cache that depend on an external resource. For example, it does not make sense to add a SqlDataReader or a FileStream to the cache. When using a SqlDataReader, you need to copy the contents of the SqlDataReader into a static representation such as an ArrayList or List collection.
- Adding Items with Dependencies: When you add an item to the Cache object, you can make the item dependent on an external object. If the external object is modified, then the item is automatically dropped from the cache.
- You can configure the size of the cache by using the web configuration file. Notice that you can’t set the size of the cache directly. However, you can specify limits on the overall memory that your application consumes, which indirectly limits the size of the cache.
private string GetDataFromCache()
{
var data = context.Cache["data"];
if (data == null)
{
lock (lockString)
{
if (data == null)
{
data = GetData();
context.Cache.Insert("data", data, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
}
}
}
return data.ToString();
}
References:
Thursday, March 4, 2010
Kentico BizForm Custom Validation
protected void Page_Init(object sender, EventArgs e)
{
BizForm.FormName = KenticoHelper.GetDocumentValueByKey("BizFormName");
BizForm.OnBeforeSave += BizForm_OnBeforeSave;
}
protected void BizForm_OnBeforeSave()
{
CMS.FormControls.FormEngineUserControl em1 = (CMS.FormControls.FormEngineUserControl)BizForm.BasicForm.FieldControls["EmailAddress"];
CMS.FormControls.FormEngineUserControl em2 = (CMS.FormControls.FormEngineUserControl)BizForm.BasicForm.FieldControls["ConfirmEmailAddress"];
string EmailAddress = em1.Value.ToString();
string ValidateEmailAddress = em2.Value.ToString();
if (EmailAddress != ValidateEmailAddress)
{
CMS.ExtendedControls.LocalizedLabel ictrl = (CMS.ExtendedControls.LocalizedLabel)BizForm.BasicForm.FieldErrorLabels["ConfirmEmailAddress"];
ictrl.Visible = true;
ictrl.Text = "The e-mail addresses do not match, please check it.";
this.BizForm.StopProcessing = true;
}
CheckBox cbAgreeTerms = (CheckBox)BizForm.BasicForm.FieldControls["AgreeTerms"];
if (!cbAgreeTerms.Checked)
{
CMS.ExtendedControls.LocalizedLabel agreeTerms_ErrorLabel = (CMS.ExtendedControls.LocalizedLabel)BizForm.BasicForm.FieldErrorLabels["AgreeTerms"];
agreeTerms_ErrorLabel.Visible = true;
agreeTerms_ErrorLabel.Text = "Field Required.";
this.BizForm.StopProcessing = true;
}
CheckBox cbUnderstandConfidential = (CheckBox)BizForm.BasicForm.FieldControls["UnderstandConfidential"];
if (!cbUnderstandConfidential.Checked)
{
CMS.ExtendedControls.LocalizedLabel understandConfidential_ErrorLabel = (CMS.ExtendedControls.LocalizedLabel)BizForm.BasicForm.FieldErrorLabels["UnderstandConfidential"];
understandConfidential_ErrorLabel.Visible = true;
understandConfidential_ErrorLabel.Text = "Field Required.";
this.BizForm.StopProcessing = true;
}
CheckBox cbUnderstandChecks = (CheckBox)BizForm.BasicForm.FieldControls["UnderstandChecks"];
if (!cbUnderstandChecks.Checked)
{
CMS.ExtendedControls.LocalizedLabel understandChecks_ErrorLabel = (CMS.ExtendedControls.LocalizedLabel)BizForm.BasicForm.FieldErrorLabels["UnderstandChecks"];
understandChecks_ErrorLabel.Visible = true;
understandChecks_ErrorLabel.Text = "Field Required.";
this.BizForm.StopProcessing = true;
}
}
Monday, January 18, 2010
WCF Basics
- A Service Contract describes what the service can do. It defines some properties about the service, and a set of actions called Operation Contracts. Operation Contracts are equivalent to web methods in ASMX, or to operation element in WSDL.
- A service contract is an interface that the WCF tools and infrastructure can convert into a WSDL document, listing the operations for a service as a series of SOAP messages and message responses.
- You provide an implementation of these methods in a class in the service. When a service executes, the WCF runtime creates a channel stack by using the bindings specified in the service configuration file and listens for client requests in the form of one of these messages. The WCF runtime then converts each SOAP message sent by a client application into a method call and invokes the corresponding method in an instance of the class implementing the service. Any data returned by the method is converted back into a SOAP response message and is sent back through the channel stack for transmission to the client application.
- WCF assumes that nothing is exposed by default. So, if you do not specify your class with Data Contract attributes, WCF doesn’t allow serialization to the wire.
Data Contracts
- Service Contracts by default, can handle simple service calls. Calls which can have simple type arguments (build-in types), and which return also simple types values. The problem comes when you want to return a custom type, or accept it as an argument for your service operation. In order to do that, the messaging world, has a concept called Data Contract. Data Contract is the normalization of your custom messaging structures. It defines the members of your operation arguments or return values. In WSDL, the Data Contract is equivalent to the type element.
References:
Thursday, January 7, 2010
Cannot resolve the collation conflict between "Latin1_General_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.
Use 'COLLATE DATABASE_DEFAULT' to resolve the collation conflict, e.g.
SELECT * FROM TableA
WHERE ID COLLATE DATABASE_DEFAULT
IN (SELECT TableAID FROM #temp)
References:
SQL SERVER – Cannot resolve collation conflict for equal to operation
Collation Conflict
Find the name of the server where the site is hosted on
1. Start a command prompt windows (start menu, click on run, type in CMD and press OK/run)
2. Type in the following command and press enter
Nslookup www.yoursite.com.au
It will return an ip – xxx.xx.xx.xxx
3. Now – we type the same command – with the ip above
Nslookup xxx.xx.xx.xxx
It will return the name of the server where the site is hosted on.
Give it a shot……… knock yourself out!
Tuesday, December 15, 2009
Filter & Sort DataTable using LINQ
Dim dt As New DataTable
dt.Load(myDataReader)
'get name of distinct root taxonomies
Dim root_names As IEnumerable(Of String) = From myRow In dt.AsEnumerable() _
Select myRow.Field(Of String)("root_name") Distinct
'get a list of the root taxonomy objects based on the name
Dim list As New List(Of Taxon.Taxon)
For Each root_name As String In root_names
Dim t As Taxon.Taxon = Taxon.TaxonDAL.Instance.GetOnName(root_name)
If t IsNot Nothing Then
list.Add(t)
End If
Next
'sort the root taxons by Product_DisplayOrder
list.Sort(Function(p1, p2) p1.Product_DisplayOrder.CompareTo(p2.Product_DisplayOrder))
For Each t As Taxon.Taxon In list
Dim currentRootName As String = t.name
'get the children of the current root taxon
Dim drRows As IEnumerable(Of DataRow) = From myRow In dt.AsEnumerable() _
Where myRow.Field(Of String)("root_name") = currentRootName _
Order By myRow.Field(Of Double)("Product_DisplayOrder") Ascending _
Select myRow
For Each rv As DataRow In drRows
Dim ThisTaxonId As String = rv("taxon_id")
Next
Next
Reference:
Wednesday, December 9, 2009
While loop in sql
--script to copy UserOrganisationId record from User table to User_Organisation
Declare @UserID as int
Declare @MaxUserID as int
Declare @OrgID int
select @UserID = MIN(intuserid) from [user]
select @MaxUserID = MAX(intuserid) from [user]
WHILE (@UserID <= @MaxUserID)
BEGIN
if exists(Select * from [user] where intuserid=@UserID)
begin
select @UserID=intuserid, @OrgID=UserOrganisationId
from [user] where intuserid = @UserID
if @orgID is not null and @orgID > 0
begin
INSERT INTO User_Organisation (UserID, OrganisationID, IsDefaultOrganisation)
VALUES (@UserID, @OrgID, 1)
end
end
set @UserID=@UserID+1
END
-- alternative script
INSERT INTO User_Organisation (UserID, OrganisationID, IsDefaultOrganisation)
SELECT intUserID, UserOrganisationId, 1
FROM [User]
WHERE (UserOrganisationId IS NOT NULL) AND (UserOrganisationId > 0)
Get comma seperated string
Public Function GetUserOrganisationIds(ByVal userID As Integer) As String
Dim dbCon As New SqlConnection(ConnectionString)
dbCon.Open()
Dim cmd As New SqlCommand("GetUserOrganisationIds", dbCon)
cmd.CommandType = CommandType.StoredProcedure
Try
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim orgList As New List(Of String)
While dr.Read
orgList.Add(dr("OrganisationID").ToString)
End While
If orgList.Count > 0 Then
Return String.Join(",", orgList.ToArray())
Else
Return ""
End If
Catch ex As Exception
Throw (ex)
Finally
dbCon.Close()
End Try
End Function
Here is how to do it in sql:
--declare holder var
DECLARE @list VARCHAR(8000)
--build comma separated list
SELECT @list = COALESCE(@list + ',', '') + CAST(DZName AS VARCHAR(5) )
FROM ClubDZlocation where ClubId = 201
--show results
SELECT @list AS 'list'
Wednesday, November 18, 2009
JQuery Validation
//if you put CssClass="required" on the dropdownlist,
//then JQuery's default required field validator will valiate the dropdownlist,
//but it only returns false if there is no items in the dropdownlist
// -------------------Custom function: Required Validator for Drop Down List----------------------------------------------------
jQuery.validator.addMethod("Validate_ddls", function(value, element) {
if (null != element) {
var iValue = new Number(element[element.selectedIndex].value);
//if ddlColumns is not populated, selectedIndex will be -1
if (iValue <= 0 iValue == NaN) {
return false;
}
else {
return true;
}
}
else {
return false;
}
}, jQuery.validator.messages.required);
// -------------------Custom function: Positive_Integer_Exclude_Zero----------------------------------------------------
jQuery.validator.addMethod("Positive_Integer_Exclude_Zero", function(value, element) {
return this.optional(element) /^[1-9]\d*$/.test(value);
}, "Positive Integer Only");
// -------------------Custom function: Positive_Integer----------------------------------------------------
jQuery.validator.addMethod("Positive_Integer", function(value, element) {
return this.optional(element) /^[0-9]\d*$/.test(value);
}, "Positive Integer Only");
// -------------------Custom function: Positive_Decimal_Exclude_Zero----------------------------------------------------
jQuery.validator.addMethod("Positive_Decimal_Exclude_Zero", function(value, element) {
return this.optional(element) /(^\d*\.?\d*[1-9]+\d*$)(^[1-9]+\d*\.\d*$)/.test(value);
}, "Invalid Amount");
// -------------------Custom function: Positive_Decimal----------------------------------------------------
jQuery.validator.addMethod("Positive_Decimal", function(value, element) {
return this.optional(element) /(^\d*\.?\d*[0-9]+\d*$)(^[0-9]+\d*\.\d*$)/.test(value);
}, "Invalid Amount");
// -------------------Custom function: Validate_Email----------------------------------------------------
jQuery.validator.addMethod("Validate_Email", function(value, element) {
return this.optional(element) /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value);
}, "Invalid Email address");
// -------------------Validate the whole Form----------------------------------------------------
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
<%=txtTag.UniqueID %>:{
required: true
},
<%=ddlTables.UniqueID %>:{
Validate_ddls: true
},
<%=ddlColumns.UniqueID %>:{
Validate_ddls: true
}
},
messages: {
<%=txtTag.UniqueID %>:{
required: "Tag is required"
},
<%=ddlColumns.UniqueID %>:{
required: "Field is required"
}
}
});
});
<script type="text/javascript" src="../include/APF_js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="../include/APF_js/jquery.validate.js"></script>
Monday, September 28, 2009
DesignMode - fix body tag as literal control
<% If DesignMode Then%><body>
<%
Else%>
<asp:Literal ID="litBodyTag" runat="server" />
<% End If%>
Monday, August 24, 2009
Load balancing issues for ASP.NET applications
There are a couple of issues we need to address because of the change:
- when put a object in session, make sure it is Serializable, so later in the clustered environment, if you manage session in sql server, it can be stored in sql server
- We were using a third party control for uploading images called I-Load which created some issues with temp image folder, luckily we fixed it. So when buying third-party control like ILoad, make sure it supports web farm
- We were using a third party control called DynamicControlsPlaceholder which does not work in cluster environment until we modified it a bit to make it work
- view state needs to have shared machinekey set up in web.config for web farm environment (in iis7 use sharekey section to share key with other web servers in the farm, then use iis7 to generate unique machinekey for every application in the iis, so that applications do not interrupt with each other)
- Cache & Application variable
- The cached object is stored in process, which means it doesn’t persist if the application domain is restarted and it can’t be shared between computers in a web farm.
- Once a worker process recycles, the entire Cache is lost because it was within this process.
- Microsoft has tried to fix this a bit with SQL Server cache invalidation (ASP.NET Cache SqlCacheDependency), but it could have potential performance issue and according to Scott Watermasysk he has not seen many be successful with this approach.
- There are a couple third party tools to fix this: Memcached ScaleOut NCache SharedCache
- The good news is Microsoft is making some strides here. They are working on an out of processing caching component called Velocity.
- We have to get rid of cache and application variables to address the problem
References:
Friday, August 14, 2009
Delete files older than certain period
Public Shared Sub ClearTemporaryFiles(ByVal folderPath As String, ByVal maxLifeTime As Integer)
Dim timeLimit As DateTime = DateTime.Now.AddMinutes(0 - maxLifeTime)
Dim filePaths() As String = System.IO.Directory.GetFiles(folderPath, "*.jpg")
For i As Integer = 0 To filePaths.Length - 1
Dim filePath As String = filePaths(i)
If (System.IO.File.GetLastWriteTime(filePath) < timeLimit) Then
Try
System.IO.File.Delete(filePath)
Catch
End Try
End If
Next
End Sub
Friday, July 24, 2009
Handle file upload timeout
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request, session not available here
'check for file upload size,
'MaxRequestLength: Int32, the maximum request size in kilobytes. The default size is 4096 KB (4 MB).
'ContentLength: Int64, the number of bytes of data to send to the Internet resource.
If ConfigurationManager.GetSection("system.web/httpRuntime").MaxRequestLength IsNot Nothing Then
Dim maxSize As Integer = CInt(ConfigurationManager.GetSection("system.web/httpRuntime").MaxRequestLength)
maxSize = maxSize * 1024
If Request.ContentLength > maxSize Then
'do not redirect to itself, it will create an infinite loop
Response.Redirect("~/ErrorPage.aspx?ErrMsg=You have reached the maximum upload file limit, please try again!")
End If
End If
End Sub
Wednesday, June 24, 2009
Javascript: Clear Form Elements
function ClearValue() {
var myContainer = document.getElementById("myFormElement");
var options = myContainer.getElementsByTagName('input');
for (i = 0; i < options.length; i++) {
var opt = options[i];
if (opt.type == 'text') {
opt.value = "";
}
else if (opt.type == 'checkbox' opt.type == 'radio') {
if (opt.checked) {
opt.checked = false;
}
}
}
var options = myContainer.getElementsByTagName('textarea');
for (i = 0; i < options.length; i++) {
var opt = options[i];
opt.value = "";
}
var options = myContainer.getElementsByTagName('select');
for (i = 0; i < options.length; i++) {
var opt = options[i];
opt.selectedIndex = -1;
}
}
Tuesday, April 21, 2009
sort table randomly
select * from(
select top 20 firstname, lastname from [user]
) as result order by NEWID()
identity_insert
set identity_insert [MyModuleElement] on
Insert into MyModuleElement
(intID, strName, strDescription, intControllerID)
Values
(48, 'test name', 'desc', 46)
set identity_insert [MyModuleElement] off
Get the current page name in javascript
<script type="text/javascript">
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
alert(sPage);
</script>
Reference:
Javascript refresh page
- location.reload(); => post request, same as click the refresh button on the browser
- window.location=window.location; => get request
- self.location=self.location; => get request
- location.replace('webform1.aspx'); => get request, does not create a history entry so browser back button disabled if no history before
- location.href='webform1.aspx'; => get request, create a history entry so browser back button works
- window.location='webform1.aspx'; => get request, create a history entry so browser back button works
IE buttons
- Back button => get request
- Forward button => post request
- Refresh button => post request
If you get an IE error saying 'To display the webpage again, Internet Explorer needs to resend the information you've previously submitted', you can use window.location=window.location; to refresh the page instead of location.reload();
Sample code:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PostMethod_Test._Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="litJavascript" runat="server"></asp:Literal>
<div>
Post:
<div>
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
Post Method:<asp:Button ID="btnPost" runat="server" Text="PostBack" />
</div>
</div>
<hr />
<div>
Redirect:
<div>
Get Method:<asp:Button ID="btnRedirect" runat="server" Text="ResponseRedirect" />
</div>
<div>
Get Method:<a href="javascript:location.replace('webform1.aspx');">JS Location Replace</a>
(does not create a history entry so browser back button disabled if no history before)
</div>
<div>
Get Method:<a href="javascript:location.href='webform1.aspx';">JS Location Href</a>
(create a history entry so browser back button works)
</div>
<div>
Get Method:<a href="javascript:window.location='webform1.aspx';">JS Window Location</a>
(create a history entry so browser back button works)
</div>
<div>
Get Method: IE Back button
</div>
<div>
Post Method: IE Forward button
</div>
</div>
<hr />
<div>
Refresh:
<div>
Get/Post Method:<a href="javascript:location.reload();">JS Location Reload</a> (if
there is any control in the form then after the form was submitted for the first
time, if you click this, it will be a post method coming with the IE alert)
</div>
<div>
Get Method:<a href="javascript:window.location=window.location;">JS Window Location</a>
(does not create a history entry) (if there is any control in the form then after
the form was submitted for the first time, if you click this, it will still be a
get method which means the form will not be submitted again)
</div>
<div>
Get Method:<a href="javascript:self.location=self.location;">JS Self Location</a>
(Same as above)
</div>
<div>
Get/Post Method: IE Refresh button - same as location.reload()
</div>
</div>
<hr />
<div>
Open New Window:
<div>
No Method:<a href="javascript:var a = window.open('webform1.aspx');">JS Window Open</a>
(just open)
</div>
<div>
Post Method for parent page:<asp:Button ID="btnOpen" Text="Open Window" runat="server" />
</div>
</div>
</div>
</form>
</body>
</html>
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub btnRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRedirect.Click
Response.Redirect("Default.aspx")
End Sub
Private Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPost.Click
End Sub
Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOpen.Click
Dim mstrMessage As New StringBuilder("")
mstrMessage.AppendFormat("<script type=""text/javascript"" >{0}", ControlChars.CrLf)
mstrMessage.AppendFormat(" window.open(""webform1.aspx"");{0}", ControlChars.CrLf)
mstrMessage.AppendFormat(" </script>")
litJavascript.Text = mstrMessage.ToString
End Sub
End Class
Friday, April 17, 2009
Reasons to Use Proxy Server
Increased internet security since:
- Users are authenticated
- Client requests are filtered
- All content, inbound and outbound, is validated
- All access is logged
- All of the internal network details are hidden
- Internet access performance is improved