public static string GetTemplate(string templateName, int PortalId)
    {
        TemplatesDataContext d = new TemplatesDataContext();
        var q = from c in d.AP_StaffBroker_Templates where c.PortalId == PortalId && c.TemplateName == templateName select c.TemplateHTML;
        if (q.Count() == 0)
        {

            var def = from c in d.AP_StaffBroker_Templates where c.PortalId == null && c.TemplateName == templateName select c;

            if (def.Count() > 0)
            {
                AP_StaffBroker_Template insert = new AP_StaffBroker_Template();
                insert.PortalId = PortalId;
                insert.TemplateDescription = def.First().TemplateDescription;
                insert.TemplateHTML = def.First().TemplateHTML;
                insert.TemplateName = def.First().TemplateName;
                d.AP_StaffBroker_Templates.InsertOnSubmit(insert);
                d.SubmitChanges();

                q = from c in d.AP_StaffBroker_Templates where c.PortalId == PortalId && c.TemplateName == templateName select c.TemplateHTML;

            }
        }

        if (q.Count() > 0)
        {
            var PS = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
            string Ministry = PS.PortalName;

            string root = DotNetNuke.Common.Globals.NavigateURL(PS.HomeTabId);
            root = root.Substring(0, root.IndexOf("/"));
            string logo = "";
            if (PS.LogoFile.Contains("http"))
                logo = PS.LogoFile;
            else
                logo = "http://" + PS.PortalAlias.HTTPAlias + PS.HomeDirectory + PS.LogoFile;
            string loginURL = DotNetNuke.Common.Globals.NavigateURL(PS.LoginTabId);

            return q.First().Replace("[MINISTRY]", Ministry).Replace("[LOGOURL]", logo).Replace("[LOGINURL]", loginURL);
        }

        else
            return "";
    }
    public static string GetTemplate(string templateName, int PortalId)
    {
        TemplatesDataContext d = new TemplatesDataContext();
        var q = from c in d.AP_StaffBroker_Templates where c.PortalId==PortalId && c.TemplateName ==  templateName select c.TemplateHTML  ;

        if (q.Count() > 0)
        {
            var PS = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
            string Ministry = PS.PortalName;

            string root = DotNetNuke.Common.Globals.NavigateURL(PS.HomeTabId);
            root=root.Substring(0,root.IndexOf("/")) ;

            string logo = "http://" + PS.PortalAlias.HTTPAlias  + PS.HomeDirectory + PS.LogoFile;

            string loginURL =   DotNetNuke.Common.Globals.NavigateURL(PS.LoginTabId) ;

            return q.First().Replace("[MINISTRY]", Ministry).Replace( "[LOGOURL]",   logo).Replace("[LOGINURL]", loginURL);
        }
        else
            return "";
    }