Blog

ASP.net: TabContainer Maintain Selected Tab Index with Cookies

Methods for reading the cookie created by the clientside script and setting the ActiveTabIndex of the TabContainer.

        private void ReadIndexCookie()
        {
            if (Request.Cookies[CookieName] != null && Request.Cookies[CookieName].Value != null)
            {
                int index;
                int.TryParse(Request.Cookies[CookieName].Value, out index);
                CurrentIndex = index;
                return;
            }
 
            CurrentIndex = 0;
        }
 
        private void SetCurrentTab()
        {
            tcStoreEditor.ActiveTabIndex = CurrentIndex;
        }

Call the two methods in the Page_Load.

        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!Page.IsPostBack)
            {
                //Some Method Calls Here
            }
 
            ReadIndexCookie();
            SetCurrentTab();
        }

JavaScript code which hooks to the TabContainer’s OnClientActiveTabChanged=”OnTabChanged” event. When that event is fired the selected tab index is pulled and written to the cookie.

<script type="text/javascript">

function Set_Cookie(name, value, expires, path, domain, secure) {
// set time, it's in milliseconds
var today = new Date();
today.setTime(today.getTime());

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));

document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}


function OnTabChanged(sender, args) {
var tabControl = $get("").control;
var currentIndex = tabControl.get_activeTabIndex();
Set_Cookie("", currentIndex, "", "", "", "");
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
width: 450px;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

ASP.net: Programmatically Checking Items in a CheckBoxList

        private void CheckItems()
        {
            foreach (string item in itemsList)
            {
                for (int i = 0; i < ckblstItems.Items.Count; i++)
                {
                    if (ckblstItems.Items[i].Text.Equals(item))
                    {
                        ckblstItems.Items[i].Selected = true;
                    }
                }
            }
        }

C#: String to Enumeration Extension Method

Here is another useful one I came across a while ago, don’t remember what site but thanks to whoever wrote it. This Extension Method takes the String and converts it to the Enumeration Type that is specified.

        /// 
        /// Converts the string to the Enumeration Type supplied.
        /// 
        /// 
        /// The String.
        /// Enumeration of Type Supplied
        /// Thrown if the string cannot be converted to the Enum type.
        /// Thrown if the string is null.
        public static T ToEnum(this string value)
        where T : struct
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }

C#: SHA1 String Hash Extension Method

In a recent project I needed the ability to take an incoming string value and calculate its SHA1 Hash in order to tell if the value had been altered in some way. Instead of creating a special utility class to accomplish this I figured a clean solution would be to just add an extension method to the String class. Here is what I came up with.

        /// 
        /// Calculates the SHA1 hash and returns it as a base64 string.
        /// 
        /// Source string to hash
        /// Base64 Hash or null.
        /// Occurs when value or key is null or empty.
        public static string GetSha1Hash(this string value)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("String is empty and not hashable.");
            Byte[] bytes = Encoding.UTF8.GetBytes(value);
            Byte[] computedHash = new SHA1CryptoServiceProvider().ComputeHash(bytes);
            return Convert.ToBase64String(computedHash);
        }

C#: ArrayList.ToList() Extension Method

I notices while working with a 3rd party component that the built-in ArrayList object in .Net does not have a built-in ToList() method to convert it to a generic List like various other list objects.
I actually prefer using generic lists much more than the standard collections since they provide tons more functionality. Because of the all this I decided it was about time I add an extension method to my library for converting ArrayLists to a typed generic list.

    public static class ArrayListExtensions
    {
        /// 
        /// Adds the ability to convert a standard
        /// ArrayList into a Generic List.
        /// 
        /// 
        /// The list.
        /// 
        public static List ToList(this ArrayList list)
        {
            List resultList = new List();
            foreach (T item in list)
            {
                resultList.Add(item);
            }
 
            return resultList;
        }
    }

DNN: Navigate from Module in a Tab to a Module in different Tab

        /// 
        /// Gets the user management URL.
        /// 
        /// The portal id.
        /// 
        protected string GetUserManagementUrl(int portalId)
        {
            int userManagementTabId = GetTabIdForCurrentPortal(AppConfiguration.UserManagementTabName);
            int moduleId = GetModuleId(userManagementTabId, AppConfiguration.UserManagementModuleName);
 
            string[] param = new string[4];
            param[0] = Constants.MODULE_ID_NAME;
            param[1] = moduleId.ToString();
            param[2] = Constants.PORTAL_ID_PARAMETER;
            param[3] = portalId.ToString();
 
            DotNetNuke.Common.Globals.ApplicationURL();
 
            return DotNetNuke.Common.Globals.NavigateURL(userManagementTabId, AppConfiguration.UserManagementControlName, param);
        }

        /// 
        /// Gets the tab id for current portal.
        /// 
        /// Name of the tab.
        /// 
        protected virtual int GetTabIdForCurrentPortal(string tabName)
        {
            TabController tabController = new TabController();
            TabInfo tabInfo = tabController.GetTabByName(tabName, PortalId);
            return tabInfo.TabID;
        }
 
        /// 
        /// Gets the tab id for portal.
        /// 
        /// Name of the tab.
        /// The portal id.
        /// 
        protected virtual int GetTabIdForPortal(string tabName, int portalId)
        {
            TabController tabController = new TabController();
            TabInfo tabInfo = tabController.GetTabByName(tabName, portalId);
            return tabInfo.TabID;
        }
 
        /// 
        /// Gets the module id.
        /// 
        /// The tab id.
        /// Name of the module.
        /// 
        protected virtual int GetModuleId(int tabId, string moduleName)
        {
            ModuleController moduleController = new ModuleController();
            Dictionary<int, ModuleInfo> genericModuleInfos = moduleController.GetTabModules(tabId);
            ModuleInfo selectedModule = null;
 
            foreach (KeyValuePair<int, ModuleInfo> pair in genericModuleInfos)
            {
                if (pair.Value.ModuleName.Equals(moduleName, StringComparison.InvariantCultureIgnoreCase))
                    selectedModule = pair.Value;
            }
 
            if (selectedModule != null)
                return selectedModule.ModuleID;
            return -1;
        }
 
        /// 
        /// Gets the user count for the passed in portal id.
        /// 
        /// The portal id.
        /// 
        protected virtual int GetPortalUserCount(int portalId)
        {
            MembershipProvider membershipProvider = MembershipProvider.Instance();
            return membershipProvider.GetUserCountByPortal(portalId);
        }