Monday, November 7, 2011

Disable caching (Browser back button problem)


When the user hit the back button a locally cached copy of the previous page is retrieved without notifying the server. As a result the Info is out of sync.

Solution 1 --> Disable caching (do not work for all browsers)
Code to disable caching (to be executed everytime thepage is loaded)

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));   //--- (-1) means the page already expired
Response.Cache.SetNoStore();  //--tell the page not to cache the page
Response.AppendHeader("Pragma", "no-cache");  //---adds a header to the HTTP response object


Solution 2 --> Use timestamps or random numbers to track pages and detect when a page is current

Monday, October 31, 2011

Copy table into new temporary table and put data back in original table


Sometimes you need to modify a table, like add a new column when there are constrains in place and you may be asked to drop the table before you can modify it. One solution is to store data in a temporary table, make the change and place the data back.

This example works when you have an identity column (autoId)

--- (1)Create new table (TempTable1) and insert into this table using SELECT INSERT
SELECT *
INTO TempTable1
FROM Table1

--- (2)Modify the Table1 --> add columns etc

--- (3)Copy the data from TempTable1 to the original Table1
---    It is important to list all the fields but the autoId (if there is one)

INSERT INTO Table1 (col1,col2,....colN)
SELECT col1,col2,....,colN
FROM TempTable1

Tuesday, October 18, 2011

New Ajax Control Toolkit Features


DATE RANGE was added (Sept. 2011). When Using the Calendar Extender, you can specify startDate and endDate, and the user can pick a date within that range.

TWITTER control
 <asp:Twitter ID="Twitter1" runat="server"  Mode="Profile" ScreenName="MyTwitterName"/>

GRAVATAR
         <ajaxToolkit:Gravatar runat="server"
            Email="myEmail@myEmail.com"
            Size="200"
            Rating="R"
            DefaultImageBehavior="Identicon"
            DefaultImage="PathToMyImage" />

Monday, October 17, 2011

Sample of COALESCE in SQL SERVER


DECLARE @List nvarchar(100)
select @List= COALESCE(@List + ',', '') + colValue  from TableFields where categoryId = 15 and LOWER(name) <> 'subject'
select @List

This will return a concatenated string with all the values (in all rows) for the column colValue and categoryId = 15. (the categoryId could be a parameter  @categoryId)

Friday, October 7, 2011

String to Date in VB.NET

Here is a simple sample to parse from string to date and then to an specific format like yyyyMMdd,
which could be handy for file naming.

 Dim strDate As String = dateExpiration.Text
 Dim parsedDate As Date

 parsedDate = DateTime.Parse(strDate)
 txtMsg.Text = parsedDate.ToString("yyyyMMdd")

Wednesday, August 24, 2011

Pad a string with zeros on the left/right in C# until completing n digits


Very simple way to pad with zeros until completing n digits
           
strMyString.PadLeft(n,'0');

Sample
string strMyString = "1234";
strMyString = strMyString.PadLeft(7,'0');


...will display "0001234"

Other notes: there is a .PadRight() function too.

Kill an Excel process in C#


foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
            {
                process.Kill();
                break;
            }
        }

Friday, August 19, 2011

Union of two dataTables and eliminate duplicates by using a customized IEqualityComparer


 public class StudentDataRowComparer : IEqualityComparer
    {

        #region IEqualityComparer Members

        public bool Equals(DataRow x, DataRow y)
        {
            return (x.Field("STUDENTID") == y.Field("STUDENTID"));
        }

        public int GetHashCode(DataRow obj)
        {
            return obj.ToString().GetHashCode();
        }

        #endregion
    }
 

How to call it
...
        //---Make an Union of both tables
        IEnumerable bothTables = dt1.AsEnumerable().Union(dt2.AsEnumerable());
                                DataTable dtUnion = bothTables.CopyToDataTable();

        //---Remove Duplicates
        var distinctStudents = dtUnion.AsEnumerable().Distinct( new StudentDataRowComparer());
                                DataTable dtFinal = distinctStudents.CopyToDataTable();

Friday, June 10, 2011

Add video to your page using HTML5

<!DOCTYPE HTML>
<html>
<body>
<video width="320" height="240" controls="controls" poster="../images/PosterImage.png">
<source src="MyVideo.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</body>
</html>

Tuesday, April 19, 2011

Sort a Listbox using IComparer in C#

What are we cooking today?
Sort a Listbox using IComparer in C# without loosing the value. 

RECIPE

The call
 SortList(MyListbox);

The Procedure

public void SortList(ListBox list)
{
        try
        {
            //---FROM LISTBOX TO LIST<>
            List ListItems = new List();
            foreach (ListItem lst in list.Items)
            {
                ListItems.Add(lst);
            }

            //---SORT LIST<>
            ListItemComparer listC = new ListItemComparer();
            ListItems.Sort(listC.Compare);

            //---CLEAR LISTBOX
            list.Items.Clear();

            //---ADD FROM ordered LIST<> to LISTBOX
            foreach (ListItem li in ListItems)
            {
                list.Items.Add(li);
            }
        }

        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
           
        }//--end catch
    }

The Icomparer: I am using this because a listitem has text and value, and we just want to order by the text, which could be a person's name or a product( the criteria could be also the value like price, personId, year...)


public class ListItemComparer : IComparer
{
    public int Compare(ListItem a, ListItem b)
    {
        int result = string.Compare(a.Text, b.Text);
        return result;
    }
}

Monday, February 28, 2011

Some helpful REGEX (regular expressions for postal code, email, phone, SIN)

What are we cooking today?
Some REGEX (Regular Expresions) for:
  • Canadian/US Postal Code
  • Email (x@x.x)
  • Phone number (xxx)(xxx-xx-xx)
  • Canadian SIN (xxx-xxx-xxx)
Recipe

Valid Canada Postal Code
(^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$)

Valid US and Canada
(\d{5}(-\d{4})?)|(^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$) )

Valid Email
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

Valid US Phone
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}

Canadian SIN
\d{3}-\d{3}-\d{3}

Thursday, February 24, 2011

Tuesday, February 8, 2011

Troubleshooting a web service consuming app error

What are we cooking today?

Troubleshooting :
"Could not find default endpoint element that references contract in the ServiceModel client configuration section"

Recipe
  1. Imagine you want to consume a web service.
  2. You created a class that have the reference to the web service
  3. You created a website (consuming application) that use the class described in (2)
When you run the web app you get this message:
"Could not find default endpoint element that references contract in the ServiceModel client configuration section"

An easy solution that worked for me: Copy all  the content of the MyClassNamespace.dll.config when you compiled your class into the web.config file of the consuming application. (The objective is to expose the endpoint and the correct contract name)

Add to web.config

















Other possible solutions I found when searching:

a) Copy config file (MyApi.dll.config) from class library to bin folder of consuming application and rename it to MyApp.config

b) Programatically create instances of Binding and RemoteAddress objects and use the constructor that takes these 2 parameters