How To Compare 2 Lists Determining If A Property Has Changed, Ignoring Order

In the list you want to perform the comparison against, override Equals

 [Serializable]
    public class AlertSubscriptionOption
    {
..
.
  /// <summary>
        /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            // Check for null values and compare run-time types.
            if (obj == null || GetType() != obj.GetType())
                return false;

            AlertSubscriptionOption p = (AlertSubscriptionOption)obj;
            return this.SubType == p.SubType;
        }

Now, to compare the 2 lists, perform the following


   
     bool subscriptionEmailDifferent = false;
   
            
    subscriptionEmailDifferent = (newSubscriptionEmailOptions.Count > 0 || oldSubscriptionEmailOptions.Count > 0) &&
                                          !newSubscriptionEmailOptions.OrderBy(x => x.SubType).ToList().SequenceEqual(oldSubscriptionEmailOptions.OrderBy(x => x.SubType).ToList());

References:

http://stackoverflow.com/questions/12795882/quickest-way-to-compare-two-list
http://stackoverflow.com/questions/188141/list-orderby-alphabetical-order

Call ASP.Net Page Method using jQuery AJAX Example

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {        
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
        
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <script src="Scripts/jquery-2.1.3.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function ShowCurrentTime() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetCurrentTime",
                    data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: OnSuccess,
                     failure: function (response) {
                         alert(response.d);
                     }
                 });
             }
             function OnSuccess(response) {
                 //alert(response.d);
                 $("#DivShowAfterClick").append("<p>" + response.d + "</p>");
                 $("#DivShowAfterClick").toggle();                
             }
        </script>

        <div>
            Your Name :
            <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
            <input id="btnGetTime" type="button" value="Show Current Time"
                onclick="ShowCurrentTime()" />
        </div>

        <div id="DivShowAfterClick" runat="server">This should be invisible until button clicked.</div>

    </form>
</body>
</html>

Source: http://aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

Clean And Simple Way To Log Entire Contents/Properties Of C# Objects

        /// <summary>
        /// Objects to XML.
        /// </summary>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public static string ObjectToXml(object output)
        {
            string objectAsXmlString;

            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                try
                {
                    xs.Serialize(sw, output);
                    objectAsXmlString = sw.ToString();
                }
                catch (Exception ex)
                {
                    objectAsXmlString = ex.ToString();
                }
            }

            return objectAsXmlString;
        }

How To Easily Add Log4Net To Your .NET Project

  1. Download Log4Net binaries –>  http://logging.apache.org/log4net/download_log4net.cgi
  2. Add Reference to Log4Net.dll in your project
  3. Create new “Logs” folder and ensure Web App/Site has Write privileges to this directory
  4. Add the following to Global.asmx
     
        /// &lt;summary&gt;
        /// Gets the application log4net log instance.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The log.&lt;/value&gt;
        public ILog log
        {
            get { return LogManager.GetLogger(&quot;AppLogger&quot;); }
        }
    
        void Application_Start(object sender, EventArgs e) 
        {
            // Code that runs on application startup
            log4net.Config.XmlConfigurator.Configure();        
    
        }
        
    
  5. Add Log4Net config section and declaration into web.config/app.config
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
      </configSections>
      <appSettings>   
      </appSettings>
      <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
          <file value="Logs/application.log"/>
          <appendToFile value="true"/>
          <rollingStyle value="Composite"/>
          <datePattern value="yyyyMMdd"/>
          <maxSizeRollBackups value="10"/>
          <maximumFileSize value="5MB"/>
          <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%n DATE: %date{MM/dd/yyyy HH:mm:ss} %n THREAD: [%thread] %n LEVEL: %-5level %n USER ID: %identity %n CLASS: %type{1} %n METHOD: %M %n LOCATION: %location %n MESSAGE: %message %n "/>
          </layout>
        </appender>
        <root>
          <level value="DEBUG"/>
          <appender-ref ref="LogFileAppender"/>
        </root>
      </log4net>
    </configuration>
    
  6. Add private static readonly property referencing ILog
      class Program
        {       
            /// &lt;summary&gt;
            /// Logging
            /// &lt;/summary&gt;
            //private readonly ILog Logger = DecisionLogManager.GetLogger(typeof(UC4Request));    
          private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
  7. Call Error method to log error
     
                catch (Exception ex)
                {
                    // Log to local log file
                    log.Error("Error", ex);
                }
    
  8. You can also call other methods (Info) to output debug information
     
             log.Info(responseOutput +
                             Environment.NewLine +
                             Base.HelperFunctions.ObjectToString(keywordClientReply, DisplayMode.HTML)
                             );
    

ASP.NET Diagnostic Page to Dump ASP.NET and Environment Configuration

<%@ Page Language="C#" AutoEventWireup="true" Trace="true" TraceMode="SortByCategory" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>ASP.NET Diagnostic Page</title>
</head>
<body>
  <form id="form1" runat="server">
  
  <h2>Environment Variables</h2>
  <pre>
  <table>  
<%
    var variables = Environment.GetEnvironmentVariables();
    foreach (DictionaryEntry entry in variables)
    {
      Response.Write("<tr><td>");
      Response.Write(entry.Key);
      Response.Write("</td><td>");
      Response.Write(entry.Value);
      Response.Write("</td></tr>");
    }
  %>
  </table>
  </pre>

  <h2>Misc</h2>
  <pre>
  Response.Filter = <%= Request.Filter.ToString() %>
  Request.ApplicationPath = <%= Request.ApplicationPath %>
  Request.PhysicalApplicationPath = <%= Request.PhysicalApplicationPath %>
  Request.PhysicalPath = <%= Request.PhysicalPath %>
  Request.UrlReferrer = <%= Request.UrlReferrer %>
  Request.UserLanguages = <%= string.Join(",", (Request.UserLanguages ?? new string[0])) %>
  </pre>
  
  </form>
</body>
</html>

Source: http://www.codeproject.com/Articles/229356/ASP-NET-Diagnostic-page-to-dump-ASP-NET-and-Enviro

Navigate To Feature In Visual Studio 2012/2013

Visual Studio’s Navigate to feature allows you to find and navigate to a specific element in your solution. Once you press the Ctrl+, combination and start typing your query*, Visual Studio will display all found elements matching your query, regardless of their type and location. To navigate to a certain element, either select it with cursor keys and press Enter or double click the element.

gte_vs[1]

Best Way To Clone An Object In .NET

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep Copy of the object.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

In case you prefer to use the new extension methods of C# 3.0, change the method to have the following signature

public static T Clone<T>(this T source)
{
   //...
}

References:
http://stackoverflow.com/questions/78536/deep-cloning-objects/78612#78612
http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects

How To Retain Leading Zeros (0) In CSV Files

When adding a value with a leading zero. for example 05710. Add additional quotes and equals:
"=""05710"""

With the CSV file resembling this:

a,b,c,d,e,f,"=""05710""",h,i

Sources:
http://social.msdn.microsoft.com/Forums/en-US/aae07b39-865f-4c68-a07f-7cad2dfd6733/how-do-i-open-csv-using-excel-without-deleting-leading-zeros?forum=isvvba
http://nebula-rnd.com/blog/tech/2009/07/excel-csv1.html

How To Test If MasterPage Content Place Holder Has Content Or Is Empty

protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
      
        DivContentAboveBottomMasthead.Visible = (HasNonEmptyControls(CphAboveBottomMasthead)) ? true : false;       
        
    }

    public static bool HasNonEmptyControls(ContentPlaceHolder cph)
    {
        if (cph.Controls.Count == 0)
        {
            return false;
        }
        else if (cph.Controls.Count == 1)
        {
            LiteralControl c = cph.Controls[0] as LiteralControl;

            if (string.IsNullOrEmpty(c.Text) || IsWhiteSpace(c.Text))
                return false;
        }

        return true;
    }

    private static bool IsWhiteSpace(string s)
    {
        for (int i = 0; i < s.Length; i++)
            if (!char.IsWhiteSpace(s[i]))
                return false;

        return true;
    }

Source

How To Use PagedDataSource To Paginate Repeater (Prev/Next/First/Last and Page Numbers)

I needed to add pagination to my Repeater control. The requirements where that a First/Last Next/Prev buttons be available as well as a list of the available pages so users could visit any page they wanted. (1 | 2 | 3..).

Below is the result using a few articles as reference for the implementation:

<%@ Page Language="C#" MasterPageFile="~/admin/paperless/Paperless.master" Inherits="Company.Common.Objects.CompanyPage"
    Title="Paperless Interest" %>

<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="Admin.Redesign.Layers" %>
<%@ Import Namespace="Admin.Redesign.Objects" %>
<%@ Import Namespace="Company.Common.Layers" %>
<%@ Import Namespace="Company.Common.Objects" %>
<%@ Import Namespace="Company.Common.Objects.DataObjects" %>

<script runat="server">       
    
    protected List<PaperlessActivity> _Reminders = new List<PaperlessActivity>();

    protected int CurrentPage
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0;	// default to showing the first page
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    protected int PageCount
    {
        get
        {
            // look for current page count in ViewState
            object o = this.ViewState["_PageCount"];
            if (o == null)
                return 1;	// default to just 1 page
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_PageCount"] = value;
        }
    }


    protected void GetItems()
    {
        PagedDataSource pagedData = new PagedDataSource();

        pagedData.AllowPaging = true;
        pagedData.PageSize = 10;
        pagedData.DataSource = PaperlessLogic.GetInterestList();
        pagedData.CurrentPageIndex = CurrentPage;


        lblCurrentPage.Text = "<b>Page:</b> " + (CurrentPage + 1).ToString() + " of " + pagedData.PageCount.ToString();

        PageCount = pagedData.PageCount;

        // Disable Prev/Next First/Last buttons if necessary
        cmdPrev.Enabled = !pagedData.IsFirstPage;
        cmdFirst.Enabled = !pagedData.IsFirstPage;
        cmdNext.Enabled = !pagedData.IsLastPage;
        cmdLast.Enabled = !pagedData.IsLastPage;



        // Wire up the page numbers
        if (pagedData.PageCount > 1)
        {
            rptPages.Visible = true;
            ArrayList pages = new ArrayList();
            for (int i = 0; i < pagedData.PageCount; i++)
                if (i == CurrentPage)
                {

                    pages.Add("<b>" + (i + 1).ToString() + "</b>");
                }
                else
                {
                    pages.Add((i + 1).ToString());
                }
            rptPages.DataSource = pages;
            rptPages.DataBind();
        }
        else
        {
            rptPages.Visible = false;
        }



        RptPaperless.DataSource = pagedData;
        RptPaperless.DataBind();
    }

    protected void cmdPrev_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the previous page
        CurrentPage -= 1;

        // Reload control
        GetItems();
    }

    protected void cmdNext_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the next page
        CurrentPage += 1;

        // Reload control
        GetItems();
    }

    protected void cmdFirst_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the first page
        CurrentPage = 0;

        // Reload control
        GetItems();
    }
    protected void cmdLast_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the last page
        CurrentPage = PageCount - 1;

        // Reload control
        GetItems();
    }

    protected void rptPages_ItemCommand(object source,
                             RepeaterCommandEventArgs e)
    {
        CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
        GetItems();
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rptPages.ItemCommand +=
           new RepeaterCommandEventHandler(rptPages_ItemCommand);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GetItems();
    }

    protected bool CurrentPageHighlight(int currPage)
    {
        return currPage == CurrentPage ? true : false;
    }
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" runat="Server">
    <asp:ScriptManager ID="ScriptManager" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
        <ContentTemplate>
            <h1>
                Paperless Interest</h1>
            <asp:Repeater ID="RptPaperless" runat="server">
                <HeaderTemplate>
                    <table class="tableData" cellpadding="0" cellspacing="0">
                        <tr>
                            <th>
                                Interest ID
                            </th>
                            <th>
                                Interest Date
                            </th>
                            <th>
                                Utility
                            </th>
                            <th>
                                OpCo
                            </th>
                            <th>
                                State
                            </th>
                            <th>
                                Channel
                            </th>
                            <th>
                                Created By
                            </th>                           
                            <th>
                                Account #
                            </th>
                            <th>
                                Customer Email
                            </th>
                            <th>
                                Customer Name
                            </th>
                        </tr>
                </HeaderTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
                <ItemTemplate>
                    <tr>
                        <td>
                            <a href="Edit.aspx?id=<%# Eval("InterestID") %>">Edit</a>:
                            <%# Eval("InterestID") %>
                        </td>
                        <td>
                            <%# Eval("CreatedDate", "{0:M/d/yyyy h:mm:ss tt}") %>
                        </td>
                        <td>
                            <%# Eval("UtilityName") %>
                        </td>
                        <td>
                            <%# Eval("OpCoNumber") %>
                        </td>
                        <td>
                            <%# Eval("StateCode") %>
                        </td>
                        <td>
                            <%# Eval("Channel.ChannelName") %>
                        </td>
                        <td>
                            <%# Eval("CreatedBy") %>
                        </td>                        
                        <td>
                            <%# Eval("CustomerAccountNumber") %>
                        </td>
                        <td>
                            <%# Eval("CustomerEmail") %>
                        </td>
                        <td>
                            <%# Eval("CustomerName") %>
                        </td>
                    </tr>
                </ItemTemplate>
            </asp:Repeater>
            <br />
            <center>
                <div>
                    <div>
                        <asp:Label ID="lblCurrentPage" runat="server"></asp:Label></div>
                    <div>
                        <table>
                            <tr>
                                <td>
                                    <asp:Button ID="cmdFirst" runat="server" Text="<< First" OnClick="cmdFirst_Click">
                                    </asp:Button>&nbsp;
                                </td>
                                <td>
                                    <asp:Button ID="cmdPrev" runat="server" Text="< Prev" OnClick="cmdPrev_Click"></asp:Button>&nbsp;
                                </td>
                                <td>
                                    <asp:Repeater ID="rptPages" runat="server">
                                        <HeaderTemplate>
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                <tr class="text">
                                                    <td>
                                        </HeaderTemplate>
                                        <ItemTemplate>
                                            <asp:LinkButton ID="btnPage" CommandName="Page" CommandArgument="<%# Container.DataItem %>"
                                                runat="server"><%# Container.DataItem %>
                                            </asp:LinkButton>&nbsp;
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            </td> </tr> </table>
                                        </FooterTemplate>
                                    </asp:Repeater>
                                </td>
                                <td>
                                    &nbsp;<asp:Button ID="cmdNext" runat="server" Text="Next >" OnClick="cmdNext_Click">
                                    </asp:Button>
                                </td>
                                <td>
                                    &nbsp;<asp:Button ID="cmdLast" runat="server" Text="Last >>" OnClick="cmdLast_Click">
                                    </asp:Button>
                                </td>
                            </tr>
                        </table>
                    </div>
                    &nbsp;</div>
            </center>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

References: