Tuesday, February 24, 2015

How To: Split Web.Config Sections To Multiple Files

Why Split Web.config Sections to multiple files :

1- Easy to maintain.
2- Organizing the Work.
3- Avoid The Error " Cannot read configuration file because it exceeds the maximum file size "

Let's begin:

- We will Split the following sections to separated files:
1- AppSettings.
2- ConnectionStrings.
3- SafeControls.
4- Bindings.
5- Client.

In every section you would like to split you should follow the following steps :

1- In Web.Config Section Cute the entire section contents.
2- Create New File and name it as you want but end with .config E.g. "appsettings.config"
3- Paste the section contents inside the file you just created plus the section tag it self


=======================================================
Web.Config :

  <appSettings file="appsettings.config">
  </appSettings>
---------------
appsettings.config : 

<?xml version="1.0" encoding="UTF-8"?>
<appSettings>
     <add key="MyKey" value="MyValue" />
     <add key="MyKey2" value="MyValue2" />
</appSettings>
---------------
=======================================================
Web.Config :

  <connectionStrings configSource="conn.config">
  </connectionStrings>
---------------
conn.config :

<connectionStrings>
       <add name="CNName" connectionString="Data Source=MyServer;Initial Catalog=MyDB;User ID=MyUser;Password=MyPassword;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>
=======================================================
Web.Config :

<SafeControls configSource="SafeControls.config">
</SafeControls>
---------------
SafeControls.config :

<SafeControls>
  <SafeControl Src="~/_controltemplates/*" IncludeSubFolders="True" Safe="True" AllowRemoteDesigner="True" SafeAgainstScript="True" />
  <SafeControl Assembly="XXX.XX.XX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXXX" Namespace="XXX.XX.XX.XX" TypeName="*" Safe="True" SafeAgainstScript="False" />
</SafeControls>
=======================================================
Web.Config :

<bindings configSource="bindings.config" />
---------------
bindings.config: 

<bindings >
</bindings>
=======================================================
Web.Config :

<client configSource="client.config" />
---------------
client.config : 

<client>
</client>



@naadydev
naadydev@outlook.com

Wednesday, February 11, 2015

Asp.Net MVC Razor Email Template

Asp.Net MVC Razor Email Template 


1- Create EmailTemplates Folder
---------------
2- Create Html Page Template Inject Razor Replacement Variables :

<h1>Test Email From NADY</h1>

<div>
    Dear @Model.UserFullName,

    Your User Name : @Model.UserName
</div>


<div>
    Your Account Start Date : @Model.RegDate
</div>

<h1>@Model.SiteUrl</h1>

---------------
3- Install RazorEngine Nuget Package:
From Nuget Consol : PM> Install-Package RazorEngine -Version 3.5.3
https://www.nuget.org/packages/RazorEngine/3.5.3
// You can also check "razormachine"->  Install-Package razormachine

More Info :
https://github.com/Antaris/RazorEngine
http://antaris.github.io/RazorEngine/
https://razorengine.codeplex.com/
----------------
4- Create your Model :
- Called "TestEmailTemplateViewModel" :

    public class TestEmailTemplateViewModel
    {
        public string UserFullName { get; set; }
        public string UserName { get; set; }
        public string RegDate { get; set; }
        public string SiteUrl { get; set; }
    }
----------------
5- Create Your test Controller "TestEmailTemplateController":

 public ActionResult TestEmailTemplate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult TestEmailTemplate(string fortest)
        {
            ParsingTemplate();
            return View();
        }

        private void ParsingTemplate()
        {
            //OR System.Web.Hosting.HostingEnvironment.MapPath(@"~/EmailTemplates/EmailTemplateTest.html");
            string templateFilePath = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailTemplateTest.html");
            var templateAsString = System.IO.File.ReadAllText(templateFilePath);

            var myViewModel = new TestEmailTemplateViewModel
            {
                UserFullName = "Mohamed Nady",
                UserName = "NADY",
                SiteUrl = "http://www.mohnady.com",
                RegDate = DateTime.Now.ToString()
            };

            var body = RazorEngine.Engine.Razor.RunCompile(templateAsString, "templateKey", typeof(TestEmailTemplateViewModel), myViewModel);
            // You Can Now Test your Returned Html Message Body (Check Body Value)

            SendEmail("naadydev@gmail.com", "m.nady@najran.gov.sa", "testEmail", body);

            //=====================================================
            //var result = RazorEngine.Engine.Razor.RunCompile("templateKey", typeof(TestEmailTemplateViewModel), myViewModel);
            //============= Simple Example ========================
            // string templateString = "Hello @Model.Name, welcome to RazorEngine!";
            // var result = RazorEngine.Engine.Razor.RunCompile(templateString, "templateKey", null, new { Name = "World" });
            //------------------------------
            //string templateString = "Hello @Model.Name, welcome to RazorEngine!";
            //string templateFileLocation = "C:/mytemplate.cshtml";
            //var result = RazorEngine.Engine.Razor.RunCompile(new LoadedTemplateSource(templateString, templateFileLocation), "templateKey", null, new { Name = "World" });
            // More Info: https://github.com/Antaris/RazorEngine
            //            http://antaris.github.io/RazorEngine/
            //======================================================
        }

        private void SendEmail(string from, string to, string subject, string body)
        {
            // Sending .net Email Code 
        }

-----------------------
6- OR you can just Use Normal .Net Way using 'MailDefinition'

        /// <summary>
        /// Other .Net Way To Send Email Using HTML Template File 
        /// Using Magic Of 'MailDefinition'
        /// </summary>
        private void OtherDotNetNormalWayToSendEmailTemplate()
        {
            //How To Use Html Template To Send Email
            string htmlBodyTemplatePath = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailTemplateTest.html");
            MailDefinition mailDefinition = new MailDefinition();
            mailDefinition.BodyFileName = Server.MapPath(htmlBodyTemplatePath);
            mailDefinition.From = "xxx";
            mailDefinition.CC = "xxx";
            mailDefinition.IsBodyHtml = true;
            mailDefinition.Subject = "xxxx";
            //------------
            System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
            replacements.Add("<%RegDate%>", "XXX");
            replacements.Add("<%UserName%>", "XXXX");
            replacements.Add("<%UserFullName%>", "XXX");
            //------------        
            System.Net.Mail.MailMessage msg = mailDefinition.CreateMailMessage("XXX", replacements, new System.Web.UI.Control());
            msg.From = new System.Net.Mail.MailAddress("XX", "XXX");
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(msg);

        }




Sending Email Using HTML File template the proper way

Sending Email Using HTML File template the proper way 

- Some Developers using variant methods to send email using html file some of them don't know the magic .Net Class "MailDefinition" .


    /// <summary>
        /// .Net Way To Send Email Using HTML Template File
        /// Using Magic Of 'MailDefinition'
        /// </summary>
        private void OtherDotNetNormalWayToSendEmailTemplate()
        {
            //How To Use Html Template To Send Email
            string htmlBodyTemplatePath = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailTemplateTest.html");
            MailDefinition mailDefinition = new MailDefinition();
            mailDefinition.BodyFileName = Server.MapPath(htmlBodyTemplatePath);
            mailDefinition.From = "xxx";
            mailDefinition.CC = "xxx";
            mailDefinition.IsBodyHtml = true;
            mailDefinition.Subject = "xxxx";
            //------------
            System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
            replacements.Add("<%RegDate%>", "XXX");
            replacements.Add("<%UserName%>", "XXXX");
            replacements.Add("<%UserFullName%>", "XXX");
            //------------      
            System.Net.Mail.MailMessage msg = mailDefinition.CreateMailMessage("XXX", replacements, new System.Web.UI.Control());
            msg.From = new System.Net.Mail.MailAddress("XX", "XXX");
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send(msg);

        }

Sunday, February 8, 2015

Fix Asp.Net MVC chrome jQuery validation: The field "MyField" must be a date.

Fix Asp.Net MVC chrome jQuery validation: The field "MyField" must be a date.

- just override jquery date validation function :

$(function () {
            $.validator.methods.date = function (value, element) {
                //Fix chrom Asp.Net MVC jQuery validation: The field "Myfield" must be a date.
                var ischrom = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
                if (ischrom) {
                    if ($.browser.webkit) {
                        //Chrome does not use the locale when new Date objects instantiated:
                        var d = new Date();
                        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
                    }
                    else {
                        return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
                    }
                }
                else
                {
                    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
                }
            };

        });

Monday, February 2, 2015

Fix SharePoint 2013 Run Configuration Wizard : An exception of type System.ServiceProcess.TimeoutException was thrown

Fix SharePoint 2013 Run Configuration Wizard : An exception of type System.ServiceProcess.TimeoutException was thrown



Reference to http://support.microsoft.com/kb/2910363 :

1- Open Windows Registry.
2- Add a new key named "AcknowledgedRunningOnAppServer" of DWORD type at the below mentioned locations:

       - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\<version>\LauncherSettings"
       - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\<version>\LoadBalancerSettings"

3- Set the value to 1.
4- Restart the System.
5- Re-Run Configuration Wizard