Thursday, March 31, 2016

MVC - Domain Route for Multi tenancy application to handle different URL

In some cases, we should handle Multi-tenant application with single code base and different domain URLs.

So how do we handle that in MVC Routing?

We have got "Constraints" concept in MVC routing, this is very helpful to filter URL based on domain also.

Okay, let us consider we have different URLs for same code base  for ex:  CompanyAName.com, CompanyBName.com. So here we have to handle two different domain URLs considering URLs already configured for same application.

routes.MapRoute(
    name: "CompanyARoute",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
    constraints: new { host = "CompanyAName.com" });


routes.MapRoute(
    name: "CompanyBRoute",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },

    constraints: new { host = "CompanyBName.com" });



This code will handle two different domains, "host" in constraints is default syntax and will map to domain automatically. here we can change default Controller, Action to anything or even we can pass some parameters. 


Suppose, if we want to add some subdomain as companyname. For ex;   DefaultURL.com/CompanyName

We can use same "Constraints" to handle this

  routes.MapRoute(
    name: "SubRoute",
    url: "{companyName}/{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
    constraints: new { companyName = "CompanyA" });


To handle multiple company names we can create more routing same like this or even in companyName we can add more like "(CompanyA|CompanyB)". "companyName" in constraints mapped to {companyName} in url.


We can utilize IRouteConstraint interface to extend each constraints attributes.

routes.MapRoute(
  name: "ConstraintRoute,
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
  constraints: new { host = new HostRouteConstraint("CompanyAName.com") });

"HostRouteConstraint" is a class extended from IRouteConstraint

using System.Web.Routing;
public class HostRouteConstraint : IRouteConstraint
    {
        private readonly string _host;

        public DomainConstraint(string host)
        {
            _host = host.ToLower();
        }

        public bool Match(HttpContextBase httpContext,
            System.Web.Routing.Route route,
            string parameterName,
            RouteValueDictionary values,
            RouteDirection routeDirection)
        {
//Here you can do your custom logic to match host
            return httpContext.Request.Url.AbsoluteUri.ToLower().Contains(_host);
        }
    }


Friday, January 8, 2016

AngularJS - Custom form validation

We can have some situation to use custom validations to our input fields, we can use following code to implement it.

Here my case is, I want to validate multiple emails field and have to show field error using AngularJS Form Validation.

For multiple email JavaScript validation check here http://rbalajiprasad.blogspot.in/2015/04/javascript-validate-multiple-email.html 

For AngularJS Form validation check here http://www.w3schools.com/angular/angular_validation.asp


HTML Page:

<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  
<span ng-show="myForm.email.$error.required">Email is required.</span>
  
<span ng-show="myForm.email.$error.validEmail">Invalid email address.</span>
  
</span>
</p>
<p>
  
<input type="button" ng-click="submit()"
  ng-disabled=
"myForm.email.$dirty && myForm.email.$invalid">
</p>


AngularJS Controller

$scope.Submit = function () {
     //your validation
            var isValidEmail = isValidEmailAddress($scope.email.ToAddress);
            $scope.myForm.email.$setValidity("validEmail", isValidEmail);

            var isValid = $scope.myForm.$valid;
            if (!isValid) { return; }

//your logic goes here

        };

Thursday, December 24, 2015

JavaScript - Simple Email without any server code

I have thought of using simple JavaScript Email feature using "mailTo:". But this is not used for bigger body contents or if you planned for much styles.

Use below JavaScript Method to send emails.

You can use more URL encode to format body.

Ref for URL Encode:  http://www.w3schools.com/tags/ref_urlencode.asp
For MailTo Documentation:  http://www.ietf.org/rfc/rfc2368.txt

JavaScript:

function SendEmail() {

   var subject = 'Mail subject goes here..';
   var body = 'Hi,%0D%0A %0D%0A' +
            'Some of your content %0D%0A%0D%0A' +
            'Next line of body goes here.%0D%0A' +
            '%E2%80%A2 Text within Bullet Text here %E2%80%A2 %0D%0A' +
           
            '%0D%0A Thanks &amp; Regards,%0D%0A' +
            'Your signature goes here..';


    window.location = 'mailto:?subject=' + subject + '&body=' + body;

    return false;

};

HTML:

<input type="button" value="Email" onclick="SendEmail();"/>

Friday, December 11, 2015

CSS - How to make two divs in equal height within container without any script

To set two divs to equal height dynamically without any scripts use this code  

<div class="equal-height-container">
            <div class="equal-height-box">
                dynamic content goes here..
            </div>
            <div class ="equal-height-box">
                dynamic content goes here..
            </div>

   </div>



.equal-height-container {
    display: table;
}

.equal-height-box {
    display: table-cell;
    height: auto;
    overflow: hidden;
    float:none;
    vertical-align:top;
}

Monday, December 7, 2015

C# - How to send email without any plugins


Below code helps to send email without any third party email plugins, but it requires SMTPServer details to be specified in web.config AppSettings. That server needs to be configured as email server.

using System.Net.Mail;
public void SendEmail(string fromAddress, string[] toAddress, string subject, string bodyContent, string[] filenames)
        {
            MailMessage email = new MailMessage();

            email.From = new MailAddress(fromAddress);
            if (toAddress != null && toAddress.Length > 0)
            {
                foreach (var toAdd in toAddress)
                {
                    email.To.Add(new MailAddress(toAdd));
                }
            }

            email.Subject = subject;
            email.Body = bodyContent;

            if (filenames != null && filenames.Length > 0)
            {
                foreach (var file in filenames)
                {
                    Attachment attachment;
                    attachment = new Attachment(@file);
                    email.Attachments.Add(attachment);
                }
            }

            try
            {
                using (var client = new SmtpClient())
                {
                    client.Send(email);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                email.Dispose();
            };
        }