European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Make a Text Chat in ASP.Net?

clock January 20, 2016 20:40 by author Peter

Now, Making Text Chat in ASP.NET Application is now easy. I am using Jaxter Chat Control. JaxterChat is an effective tool for nurturing online communities within your website. By combining the rapid response of ajax with the power and flexibility os ASP.NET, JaxterChat provides a stylish alternative to traditional Flash and Java chat clients. JaxterChat supports a rich designer interface for previewing the appearance of the control at design time. Display properties can be adjusted and the effects of these changes are reflected instantly in the Visual Studio designer view.

We are going to working with Text Chat using Jaxter Chat control in ASP.NET.  Now, write the following code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 
<%@ Register assembly="JaxterChat" namespace="WebFurbish" 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 runat="server"> 
<title></title> 
</head> 
<body style="height: 316px"> 
<form id="form1" runat="server"> 
<div> 
    <cc1:JaxterChat ID="JaxterChat1" runat="server" BackColor="#A0AB9D" BackImageUrl="JaxterChat/Themes/Googleish/back_strip_4.jpg" ClearPageButtonImageUrl="JaxterChat/Images/clear_page.gif" EmoticonsButtonImageUrl="JaxterChat/Images/emoticons.gif" FontColor="MidnightBlue" FontFace="Arial, Verdana" FontSizePixels="12" FooterPanelHeightPixels="0" HeaderPanelHeightPixels="23" Height="300px" MessageInputBackColor="White" MessageInputBorderColor="DarkGray" MessageInputBorderWidthPixels="1" MessageInputFontColor="Black" MessageInputFontFace="Arial, Verdana" MessageInputFontSizePixels="12" MessageInputHeightPixels="38" MessageInputPaddingBottomPixels="1" MessageInputPaddingLeftPixels="1" MessageInputPaddingRightPixels="1" MessageInputPaddingTopPixels="1" MessageOutputBackColor="White" MessageOutputBorderColor="DarkGray" MessageOutputBorderWidthPixels="1" MessageOutputFontColor="Black" MessageOutputFontFace="Arial, Verdana" MessageOutputFontSizePixels="12" MessageOutputLinkColor="90, 128, 198" MessageOutputPaddingBottomPixels="1" MessageOutputPaddingLeftPixels="8" MessageOutputPaddingRightPixels="1" MessageOutputPaddingTopPixels="2" MessageOutputPostIconUrl="JaxterChat/Themes/Googleish/icon.gif" MessageOutputUserNameFontColor="Black" PaddingBottomPixels="5" PaddingLeftPixels="4" PaddingRightPixels="4" PaddingTopPixels="3" PopupCloseButtonImageUrl="JaxterChat/Images/popup_close.gif" PopupWindowBackColor="Gainsboro" PopupWindowContentFontColor="Black" PopupWindowContentFontFace="Arial, Verdana" PopupWindowContentFontSizePixels="10" PopupWindowTitleFontColor="Black" PopupWindowTitleFontFace="Arial, Verdana" PopupWindowTitleFontSizePixels="12" ScrollBarIE3DLightColor="White" ScrollBarIEArrowColor="LightGray" ScrollBarIEBaseColor="Silver" ScrollBarIEDarkShadowColor="Silver" ScrollBarIEFaceColor="White" ScrollBarIEHighlightColor="AliceBlue" ScrollBarIEShadowColor="Silver" ScrollBarIETrackColor="Gainsboro" SendButtonImageUrl="JaxterChat/Images/send_button.gif" ShowSendButton="False" ToggleSoundOffButtonImageUrl="JaxterChat/Images/sound_off.gif" ToggleSoundOnButtonImageUrl="JaxterChat/Images/sound_on.gif" ToolbarPanelHeightPixels="21" UserListButtonImageUrl="JaxterChat/Images/users.gif" Width="359px"> 
    </cc1:JaxterChat> 
    <br /> 
</div> 
</form> 
</body> 
</html> 

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Fixing the Error logging and Exception handling?

clock January 6, 2016 21:10 by author Peter

The errors and exceptions are going to be written to a text file because it is simpler to search out the reason for the error because the Error Log text file are often easily opened using the basic notepad application in Windows.

The following HTML Markup consists of an ASP.NET Button control which will raise an Exception and the exception (error) Message details will be displayed.
<asp:Button Text="Click to Raise Exception" runat="server" OnClick="RaiseException"/>

Namespaces
You will need to import the following namespace.
C#
using System.IO;

VB.Net
Imports System.IO

Creating simple Error Log Text File in ASP.NET
The following event handler is raised when the Button is clicked. An exception is raised by converting a string value to integer inside a Try-Catch block.
The raised Exception is caught in the Catch block and the LogError function is called.
Inside the LogError function, the details of the exception (error) are written to an Error Log Text file along with current date and time.


C#
protected void RaiseException(object sender, EventArgs e)
{
try
{
    int i = int.Parse("Mudassar");
}
catch (Exception ex)
{
    this.LogError(ex);
}
}

private void LogError(Exception ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using (StreamWriter writer = new StreamWriter(path, true))
{
    writer.WriteLine(message);
    writer.Close();
}
}


VB.Net
Protected Sub RaiseException(sender As Object, e As EventArgs)
Try
    Dim i As Integer = Integer.Parse("Mudassar")
Catch ex As Exception
    Me.LogError(ex)
End Try
End Sub

Private Sub LogError(ex As Exception)
Dim message As String = String.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"))
message += Environment.NewLine
message += "-----------------------------------------------------------"
message += Environment.NewLine
message += String.Format("Message: {0}", ex.Message)
message += Environment.NewLine
message += String.Format("StackTrace: {0}", ex.StackTrace)
message += Environment.NewLine
message += String.Format("Source: {0}", ex.Source)
message += Environment.NewLine
message += String.Format("TargetSite: {0}", ex.TargetSite.ToString())
message += Environment.NewLine
message += "-----------------------------------------------------------"
message += Environment.NewLine
Dim path As String = Server.MapPath("~/ErrorLog/ErrorLog.txt")
Using writer As New StreamWriter(path, True)
    writer.WriteLine(message)
    writer.Close()
End Using
End Sub

And here is the output:

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



European ASP.NET 4.5 Hosting - UK :: How to Improve Your Entity Framework Performance

clock November 23, 2015 23:46 by author Scott

LINQ to Entity is a great ORM for querying and managing databases. There are some points that we should consider while designing and querying databases using the Entity Framework ORM.

Disable change tracking for entity if not needed

In the Entity Framework, the context is responsible for tracking changes in entity objects. Whenever we are only reading data, there is no need to track the entity object. We can disable entity tracking using the MergeOption, as in:

AdventureWorksEntities e = new AdventureWorksEntities();
e.EmployeeMasters.MergeOption = System.Data.Objects.MergeOption.NoTracking;

Use Pre-Generating Views to reduce response time for the first request

While working with Entity Framework, view generation may take longer for a large and complicated model. We can use a pre-generated view to save run time cost to generate a view for the first request of a page. A Model Generated view helps us to improve start-up performance at run time.

Avoid fetching all the fields if not required

Avoid fetching all fields from the database that are not really required. For example we have an EmployeeMaster table and for some operation I require only the EmployeeCode field so the query must be:

AdventureWorksEntities e = new AdventureWorksEntities();
string
 code = e.EmployeeMasters.Where(g => g.EmployeeId == 1000)
                                                             .Select(s => s.EmployeeCode).FirstOrDefault();

Retrieve only required number of records (rows)

Do not collect all data while binding data to a data grid. For example if we have a data grid on a page and we only show 10 records on the screen, so do not fetch all records from the database, as in:

AdventureWorksEntities e = new AdventureWorksEntities();
int
 pageSize = 30, startingPageIndex = 3;
List<EmployeeMaster> lstemp = e.EmployeeMasters
                                                           .Take(pageSize)
                                                           .Skip(startingPageIndex * pageSize).ToList();

Avoid using Contains

Avoid use of the contain keyword with a LINQ - Entity Query. While Entity Framework generates equivalent SQL, the contain is converted in the "WHERE IN" clause. The "IN" clause has performance issues.

Avoid using Views

Views degrade the LINQ query performance. So avoid using views in LINQ to Entities.

Use Compiled Query

If you are using Entity Framework 4.1 and below, you must use a compiled query. The Compiled Query class provides compilation and caching of queries for reuse. The Entity Framework 5.0 supports a new feature called Auto-Compiled LINQ Queries. With EF 5.0, LINQ to Entity queries are compiled automatically and placed in EF's query cache, when executed.

static Func<AdventureWorksEntitiesIQueryable<EmployeeDetail>> getEmpList = (
            CompiledQuery.Compile((AdventureWorksEntities db) =>
                db.EmployeeDetails
            ));

AdventureWorksEntities e = new AdventureWorksEntities1();
List
<EmployeeDetail> empList = getEmpList(e).ToList();

Must examine Queries before being sent to the Database

When we are investigating performance issues, sometimes it's helpful to know the exact SQL command text that the Entity Framework is sending to the database. I would suggest that we must examine each and every LINQ to Entity queries to avoiding performance issues.

Efficiently Loading Related Data

Entity Framework supports the loading of related data. The Include method helps us load relevant data. Use of the Include method ensures it is really required for the page i.e. do not include a navigation property whenever it is not really required.

Select appropriate Loading type while defining model

Entity Framework supports three ways to load related data: eager loading, lazy loading and explicit loading. Eager loading is the process in which a query of one type of entity also loads related entities as part of the query. Eager loading is done by use of the Include method. Lazy loading is the process in which an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When lazy loading disabled, it is possible to lazily load related entities with use of the Load method on the related entity's entry. It is called explicit loading. So depending upon on the type of application and requirement we can select appropriate Loading type for the entity model.

Conclusion

Using the above definition tips, we can definitely improve the performance of LINQ to Entity Queries.



European ASP.NET 4.5 Hosting - UK :: How to Check that .NET has been Installed on the Server

clock November 16, 2015 21:51 by author Scott

Most of the newbies and few administrators handling the deployment of their company’s ASP.Net applications on the Windows Server must be knowing about the basics of how ASP.Net is associated with the IIS web server. Here’s a quick tip for you to quickly check  whether the exact version of .NET framework has been installed on the Server and also to check whether it has been registered with the IIS or not.

In this scenario, I'm going to consider a fresh installation of the Windows Server (2008 R2/ 2012 R2). SO make sure you have the below mentioned configuration done accordingly.

How to Find The Existence of the .NET Framework and Its Files

Navigate to this location, to make sure the .Net Framework that you are wanting/looking for is installed.

File location: (32-bit): C:\Windows\Microsoft.NET\Framework\ (By default)
For 64-bit: C:\Windows\Microsoft.NET\Framework64\ (By default)

There are several .NET Framework versions available. Some are included in some Windows OS by default and all are available to download at Microsoft website as well.

Following is a list of all released versions of .NET Framework:

- .NET Framework 1.0 (Obsolete)
- .NET Framework 1.1 (Obsolete, comes installed in Windows Server 2003)
- .NET Framework 2.0* (Obsolete, comes as a standalone installer)
- .NET Framework 3.0* (comes pre-installed in Windows Vista and Server 2008)
- .NET Framework 3.5* (comes pre-installed in Windows 7 and Server 2008 R2)
- .NET Framework 4.0*
- .NET Framework 4.5* (comes pre-installed in Windows 8/8.1 and Server 2012/2012 R2)

Note: The framework marked with (*) have their later versions which is available as service packs, that can be downloaded from Microsoft’s Download website.

To check the ASP.Net application version compatibility, refer this MSDN article. Which is also shown below

If you find the respective folder, say v4.0.xxx, then it means that the Framework 4.0 or above has been installed. X:\Windows\Microsoft.NET\Framework\v4.0.30319  (The X:\ is replaced by the OS drive)

Also you will find a similar folder for the x64 bit .Net Framework and its files associated in this location X:\Windows\Microsoft.NET\Framework64\v4.0.30319 (The X:\ is replaced by the OS drive)

This can also be confirmed using another method by navigating into the Windows Registry to find a key and its existence confirms the same.

How to Find the .NET Framework Versions by Viewing the Registry

1. On the Start menu, choose Run.

2. In the Open box, enter regedit.exe.

You must have administrative credentials to run regedit.exe.

In the Registry Editor, open the following subkey:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

This confirms the existence of .Net framework 4 and above(4.5 / 4.5.1 / 4.5.2 Only).

In most of the cases people might ignore this, assuming they have already configured ASP.Net by choosing from the server roles or any other version of .Net application that was working earlier.

This step will guide you to check whether your new application (with respect to the .Net Framework compatibility) has its asp.net component registered or not.

Simply Check ASP.NET 4.5 has been Installed via IIS

To check that .net 4.5 has been installed on the server, please just simply create a website in IIS and hit the “Select” button to check the .Net framework versions available to create Application Pool.

If you find v4.5 instead of v4.0, then it clearly justifies that .Net framework version 4.5 or above (4.5 / 4.5.1 / 4.5.2 only) has been installed and made available to run any website that requires this framework’s version.

If you don't find it, then navigate to the framework’s root folder (refer pic 2) and run “aspnet_regiis.exe” which will in turn register the asp.net component to the IIS.

Once you have registered the ASP.Net component, restart the IIS from the command prompt by typing “iisreset”, then launch your IIS Manager and follow the Step 3, to check the version listed in the available frameworks in the “Add Website” windows as shown above.

Now you are all set to go and start deploying your web application through Web Deploy / FTP or any other.



European ASP.NET 4.5. Hosting - France :: Memory Leak in .Net 4.5

clock November 9, 2015 23:57 by author Scott

One of the common issues with events and event handlers is memory leaks. In applications, it is possible that handlers attached to event sources will not be destroyed if we forget to unregister the handlers from the event. This situation can lead to memory leaks. .Net 4.5 introduces a weak event pattern that can be used to address this issue.

Problem: Without using weak event pattern.

Let's understand the problem with an example. If we understand the problem then the solution is very easy.

public class EventSource  
{  
        public event EventHandler<EventArgs> Event = delegate { };    

        public void Raise()  
        {  
            Event(this, EventArgs.Empty);  
        }          
}    
  

public class EventListener   
{  
        public int Counter { getset; }  
        EventSource eventSourceObject;    

        public EventListener(EventSource source)  
        {  
            eventSourceObject= source;  
            eventSourceObject.Event += MyHandler;  
        }           

        private void MyHandler(object source, EventArgs args)  
        {  
            Counter++;  
            Console.WriteLine("MyHandler received event "+ Counter);  
        }    

        public void UnRegisterEvent()  
        {  
            eventSourceObject.Event -= MyHandler;  
        }  
}  
static void Main(string[] args)  
{              
         EventSource source = new EventSource();  
         EventListener listener = new EventListener(source);  
         Console.WriteLine("Raise event first time");  
         Console.Read();  
         source.Raise();    

         //Set listener to null and call GC to release the  
        //listener object from memory.    

         Console.WriteLine("\nSet listener to null and call GC");  
         Console.Read();  
        //developer forget to unregister the event                 

        //listener.UnRegisterEvent();  
         listener = null;  
         GC.Collect();  
         Console.WriteLine("\nRaise event 2nd time");  
         Console.Read();  
         source.Raise();  
         Console.ReadKey();                  
}  

Output

The developer is expecting that set listener = null is sufficient to release the object but this is not the case. The event listener object is still in memory.

the EventListener's handler should be called a second time. But it's calling.

In this example the developer forget to unregister the event. With this mistake, the listener object is not released from memory and it's still active. If we call the unregister method then the EventListener would be released from memory. But the developer does not remember when to unregister the event.

This is the problem!

Solution: Weak event pattern.

The weak event pattern is designed to solve this memory leak problem. The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister. 

In the old way of attaching the event with a source it is tightly coupled.

eventSourceObject.Event += MyHandler;  

Using Weak event pattern

Replace the preceding registration with the following code and run the program.

WeakEventManager<EventSource, EventArgs>.AddHandler(source, "Event", MyHandler);

After raising the event a second time, the listener is doing nothing. It means the listener is no longer in memory. 

Now the developer need not be concerned about calling the unregister event.

For any specific scenario if we want to unregister the event then we can use the RemoveHandler method as in the following:

WeakEventManager<EventSource, EventArgs>. RemoveHandler(source, "Event", MyHandler);  



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Edit value of RequiresQuestionAndAnswer in ASP.NET 4.6 Membership Provider

clock October 29, 2015 01:16 by author Peter

Let me show you how to edit value of RequiresQuestionAndAnswer in ASP.NET 4.6 Membership provider. RequiresQuestionAndAnswer is checked when ResetPassword or GetPassword is called. The provider provided with the .NET Framework throws a NotSupportedException if RequiresQuestionAndAnswer is true and the supplied password answer is null. Requiring a password question and answer provides an additional layer of security when retrieving or resetting a user's password. Users can supply a question and answer when their user name is created that they can later use to retrieve or reset a forgotten password.

A Membership Provider allows a web application to store and retrieve membership data for a user, and the standard ASP.NET Membership Provider uses pre-defined SQL Server tables.

Now you write the following example code:
MembershipUser user = Membership.GetUser();
string newPassword = "newPass";
string tempPassword = string.Empty;
if (Membership.Provider.RequiresQuestionAndAnswer)
{
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
}
else
{
tempPassword = user.ResetPassword();
}

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Hosting with Toronto Data Center - HostForLIFE.eu :: How To Convert A Password Into Complicated

clock October 27, 2015 00:22 by author Rebecca

In this tutorial, we will show you how to convert a password into complicated in ASP.NET. We will ise SHA1 or MD5 algorithm to work around for converting your password into complicated.

Follow these steps to make your password seems complicated in ASP.NET:

Step 1

Open Visual Studio and create an empty website. Give it a suitable name for example: [hashpass_demo].

Step 2

 In Solution Explorer you will get your empty website, then add a Web Form by going like this:

  • Right Click
  • Add New Item, then Web Form. Name it hashpass_demo.aspx.

Step 3

Now mcreate some design for your application by going to hashpass_demo.aspx and try the code like this:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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> 
        <style type="text/css"> 
            .style1 
            { 
                width: 258px; 
            } 
            .style2 
            { 
                width: 239px; 
            } 
        </style> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div> 
         
            <table style="width:100%;"> 
                <tr> 
                    <td class="style1"> 
                        Enter Your Username:</td> 
                    <td class="style2"> 
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
                    </td> 
                    <td> 
                        <asp:Label ID="Label2" runat="server"></asp:Label> 
                    </td> 
                </tr> 
                <tr> 
                    <td class="style1"> 
                        Enter Your Password:  
                    </td> 
                    <td class="style2"> 
                        <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox> 
                    </td> 
                    <td> 
                        <asp:Label ID="Label1" runat="server"></asp:Label> 
                    </td> 
                </tr> 
                <tr> 
                    <td class="style1"> 
                         </td> 
                    <td class="style2"> 
                         </td> 
                    <td> 
                         </td> 
                </tr> 
                <tr> 
                    <td class="style1"> 
                         </td> 
                    <td class="style2"> 
                        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /> 
                    </td> 
                    <td> 
                         </td> 
                </tr> 
            </table> 
         
        </div> 
        </form> 
    </body> 
    </html> 

Your design will look like following picture snippet:

Step 4

Now it’s time for server side coding so that our application starts working. Open your hashpass_demo.aspx.cs file and code it like below:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.Security; 
     
    public partial class _Default : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
     
        } 
        protected void Button1_Click(object sender, EventArgs e) 
        { 
            string securepass = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "MD5"); 
            Label2.Text = "Your Username is-" + TextBox1.Text; 
            Label1.Text = "Your HashPassword is-" + securepass; 
            Label2.ForeColor = System.Drawing.Color.ForestGreen; 
            Label1.ForeColor = System.Drawing.Color.ForestGreen; 
       
        } 
    } 

Here is the output:

Good luck!

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.6 Hosting with Milan Data Center - HostForLIFE.eu :: How To Delete Duplicates Elements from List Using IEqualityComparer?

clock October 22, 2015 00:03 by author Peter

In this tutorial, let me show you how to delete duplicates elements from list using IEqualityComparer in ASP.NET 4.6. IEqualityComparer is implemented by classes that need to support an equality comparison for two values of the same type. Generic collections require instances of classes that implement the IEqualityComparer interface in order to provide support for custom data types. IEqualityComparer has two methods to support the comparison of objects for equality. Let us suppose that you have a Employee class that has four properties EmployeeID,FirstName,LastName and Age. Now, you need to write the following code:

public class Employee
{
public Employee()
{
}
public string EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public List&lt;Employee&gt; Employees
{
    get
    {
return new List&lt;Employee&gt;()
        {
new Employee(){EmployeeID="01",FirstName="Peter",LastName="Last01",Age=31},
new Employee(){EmployeeID="02",FirstName="Scott",LastName="Last02",Age=35},
new Employee(){EmployeeID="03",FirstName="Rebecca",LastName="Last03",Age=36},
new Employee(){EmployeeID="01",FirstName="Paul",LastName="Last01",Age=31},
new Employee(){EmployeeID="01",FirstName="Richard",LastName="Last01",Age=31},
        };
    }
}
}

In the above class I have added some dummy records which have duplicates elements. Now,let's remove the duplicate elements from the above class using IEqualityComparer interface.  For this right click on the project and add a new class named EmployeeEquality and inherit this class with IEqualityComparer and write the below code:
public class EmployeeEquality : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (x.EmployeeID == y.EmployeeID && x.FirstName == y.FirstName && x.LastName == y.LastName && x.Age == y.Age)
return true;
return false;
}
public int GetHashCode(Employee obj)
{
//For shake of simplicity
return obj.FirstName.GetHashCode();
}
}


Now,let's display the record on UI. First, right click on the project and add new page,and add the below code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="btnUnSorted" runat="server" OnClick="btnUnSorted_Click" Text="Duplicates" />
<asp:Button ID="btnWDuplicate" runat="server" OnClick="btnWDuplicate_Click" Text="Without Duplicate" />
</form>
</body>
</html>

In the code behind add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUnSorted_Click(object sender, EventArgs e)
{
    Employee employee = new Employee();
    GridView1.DataSource = employee.Employees;
    GridView1.DataBind();
}
protected void btnWDuplicate_Click(object sender, EventArgs e)
{
    Employee employee = new Employee();
    List<Employee> list = employee.Employees;
    var distinctEmployee = list.Distinct(new EmployeeEquality());
    GridView1.DataSource = distinctEmployee;
    GridView1.DataBind();
}
}

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.6 Hosting Germany - HostForLIFE.eu :: How to Use C# to Track an IP Address

clock October 5, 2015 18:25 by author Rebecca

In this tutorial, you will learn how to track an IP address in ASP.NET using C#.

In ASP.NET it is also very easy to find IP address no matter whether user is behind the proxy or not, you can easily track the user in ASP.NET. So let's have a look over the following code:

    //To get the ip address of the machine and not the proxy use the following code      
                string strIPAddress = Request.UserHostAddress.ToString(); 
                strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
     
                if (strIPAddress == null || strIPAddress == "") 
                { 
                    strIPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString(); 
                } 

That's it! Easy right?

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.6 Hosting Portugal - HostForLIFE.eu :: How to Use Script to Disable Auto Fill TextBoxes in Some Browsers

clock September 26, 2015 12:59 by author Rebecca

Recent's browsers like Chrome, Firefox, Internet Explorer and Safari has functionality of auto complete values in TextBoxes. If you have enabled this features in browser, every time you start to enter value in TextBox you get a drop down of prefilled values in that TextBox. This feature of browser can be disabled by the programming for a specific web form like payment form and other confidential information form of a web application.

In chrome browser, you can enable auto-fill as shown below:

Step 1

Then you will have a below form for online payment of product by credit card or debit card then it is mandatory to stop auto complete functionality of browser so that browser doesn’t save the confidential information of a customer’s credit card or debit card.

 

Step 2


Then, you can turn off auto-fill for your complete form by setting autocomplete attribute value to off as shown below:

<form id="Form1" method="post" runat="server" autocomplete="off">

 .

 .

</form>

Step 3

You can also turn off auto-fill for a particular TextBox by setting autocomplete attribute value to off as shown below:

<asp:TextBox Runat="server" ID="txtConfidential" autocomplete="off"></asp:TextBox>

Step 4

And you can also do this from code behind also like as:

txtConfidential.Attributes.Add("autocomplete", "off");

After doing one of above code you will see that there is no auto-fill.


HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in