Securely post multiple models in one request in MVC application

Securely post multiple models in one request in MVC application

Real-Time Sample: CRM in MVC

Suppose we have a requirement of adding a customer with Their Branch, Follow up details

Step 1: Firstly make jquery object models to be post data in single request

Customer Model
var customerViewModel = {
CustomerId: hdnCustomerId.val(),
CustomerCode: txtCustomerCode.val().trim(),
CustomerName: txtCustomerName.val().trim(),
ContactPersonName: txtContactPersonName.val().trim(),
Designation: txtDesignation.val().trim(),
Email: txtEmail.val().trim(),
MobileNo: txtMobileNo.val().trim(),
ContactNo: txtContactNo.val(),
Fax: txtFax.val().trim(),
PrimaryAddress: txtPrimaryAddress.val().trim(),
City: txtCity.val().trim(),
StateId: ddlState.val(),
CountryId: ddlCountry.val(),
PinCode: txtPinCode.val().trim(),
CSTNo: txtCSTNo.val().trim(),
TINNo: txtTINNo.val().trim(),
PANNo: txtPANNo.val().trim(),
GSTNo: txtGSTNo.val().trim(),
ExciseNo: txtExciseNo.val().trim(),
EmployeeId: hdnEmployeeId.val(),
CustomerTypeId: ddlCustomerType.val(),
CreditLimit: txtCreditLimit.val().trim(),
CreditDays: txtCreditDays.val().trim(),
Customer_Status: chkStatus,
AnnualTurnOver:txtAnnualTurnOver.val(),
GST_Exempt: GSTExempt

};

Customer Branch Model
var customerBranch = {
CustomerBranchId: customerBranchId,
BranchName: branchName,
ContactPersonName: bContactPersonName,
Designation: bDesignation,
Email: bEmail,
MobileNo: bMobileNo,
ContactNo: bContactNo,
Fax: bFax,
PrimaryAddress: bAddress,
City: bCity,
StateId: bStateId,
StateName: bStateName,
CountryId: bCountryId,
PinCode: bPinCode,
CSTNo: bCSTNo,
TINNo: bTINNo,
PANNo: bPANNo,
GSTNo: bGSTNo,
AnnualTurnOver:annualTurnOverBranch

};
customerBranchList.push(customerBranch);

Cstomer Follow Up Model
var customerFollowup = {
CustomerFollowUpId: CustomerFollowUpId,
FollowUpActivityTypeId: FollowUpActivityTypeId,
FollowUpActivityTypeName: FollowUpActivityTypeName,
FollowUpDueDateTime: FollowUpDueDateTime,
FollowUpReminderDateTime: FollowUpReminderDateTime,
FollowUpRemarks: FollowUpRemarks,
Priority: Priority,
PriorityName: PriorityName,
FollowUpStatusId: FollowUpStatusId,
FollowUpStatusName: FollowUpStatusName,
FollowUpStatusReason: FollowUpStatusReason,
FollowUpByUserId: FollowUpByUserId,
FollowUpByUserName: followUpByUserName
};

customerFollowUpList.push(customerFollowup);

Step 2: Make ajax call to be post data

var requestData = {
customerViewModel: customerViewModel,
customerBranchs: customerBranchList,
customerProducts: customerProductList,
customerFollowUps: customerFollowUpList };
$.ajax({
url: “../Customer/AddEditCustomer”,
cache: false,
type: “POST”,
dataType: “json”,
data: JSON.stringify(requestData),
contentType: ‘application/json’,
success: function (data) {
if (data.status == “SUCCESS”) {
ShowModel(“Alert”, data.message);
ClearFields();
setTimeout(
function () {
window.location.href = “../Customer/AddEditCustomer”;
}, 2000);

$(“#btnSave”).show();
$(“#btnUpdate”).hide();
}
else {
ShowModel(“Error”, data.message)
}
},
error: function (err) {
ShowModel(“Error”, err)
}
});

Step 3: Pass data to Action Method to be perform data

public ActionResult AddEditCustomer(CustomerViewModel customerViewModel, List<CustomerBranchViewModel> customerBranchs, List<CustomerProductViewModel> customerProducts,List<CustomerFollowUpViewModel> customerFollowUps)
{ }

If any issues contact with us on : http://www.dotnethub.co.in/contact-us

Implement google recaptcha in MVC and Asp.NET application

Step 1: Generate Site Key and Secret Key for recaptcha

Go through the link: https://www.google.com/recaptcha

Then generate you Site Key and Secret Key like below image

 

Google recaptcha

Step 2: Make div like this on your page where you want to implement captcha

<div id=”CaptchaVal” class=”g-recaptcha” data-sitekey=”Your Site Key“></div>

Step 3: Validate you captcha code by this server side code

public static bool ValidateCaptcha(string response)
{
string secretkey = System.Configuration.ConfigurationManager.AppSettings[“secretkey”];
string secret = secretkey;
var client = new WebClient();
var reply = client.DownloadString(string.Format(“https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}”, secret, response));
var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);
return Convert.ToBoolean(captchaResponse.Success);
}

if any issue you can contact with us on

http://www.dotnethub.co.in/contact-us

Post multiple entities in single request MVC

Post Multiple Entities in single request in Linq:

public ResponseOut AddEditCustomer(CustomerViewModel customerViewModel, List<CustomerBranchViewModel> customerBranchs, List<CustomerProductViewModel> customerProducts,List<CustomerFollowUpViewModel> customerFollowUps)
{
ResponseOut responseOutBranch = new ResponseOut();
ResponseOut responseOutProduct = new ResponseOut();
ResponseOut responseOut = new ResponseOut();
ResponseOut responseOutSL = new ResponseOut();
ResponseOut responseOutFollowUp = new ResponseOut();
using (TransactionScope transactionscope = new TransactionScope())
{
try
{
Customer customer = new Customer
{
CustomerId = customerViewModel.CustomerId,
CustomerCode = customerViewModel.CustomerCode,
CustomerName = customerViewModel.CustomerName,
ContactPersonName = customerViewModel.ContactPersonName,
Designation = customerViewModel.Designation,
Email = customerViewModel.Email,
MobileNo = customerViewModel.MobileNo,
ContactNo = customerViewModel.ContactNo,
Fax = customerViewModel.Fax,
PrimaryAddress = customerViewModel.PrimaryAddress,
City = customerViewModel.City,
StateId = customerViewModel.StateId,
CountryId = customerViewModel.CountryId,
PinCode = customerViewModel.PinCode,
CSTNo = customerViewModel.CSTNo,
TINNo = customerViewModel.TINNo,
PANNo = customerViewModel.PANNo,
GSTNo = customerViewModel.GSTNo,
ExciseNo = customerViewModel.ExciseNo,
EmployeeId = customerViewModel.EmployeeId,
CustomerTypeId = customerViewModel.CustomerTypeId,
CompanyId = customerViewModel.CompanyId,
CreatedBy = customerViewModel.CreatedBy,
CreditLimit=customerViewModel.CreditLimit,
CreditDays=customerViewModel.CreditDays,
Status = customerViewModel.Customer_Status,
AnnualTurnover = customerViewModel.AnnualTurnover,
GST_Exempt = customerViewModel.GST_Exempt
};

int customerId = 0;
responseOut = dbInterface.AddEditCustomer(customer, out customerId);

if (responseOut.status == ActionStatus.Success)
{
if (customerBranchs != null && customerBranchs.Count > 0)
{
foreach (CustomerBranchViewModel customerBranchViewModel in customerBranchs)
{
CustomerBranch customerBranch = new CustomerBranch
{
CustomerId = customerId,
CustomerBranchId = customerBranchViewModel.CustomerBranchId,
BranchName = customerBranchViewModel.BranchName,
ContactPersonName = customerBranchViewModel.ContactPersonName,
Designation = customerBranchViewModel.Designation,
Email = customerBranchViewModel.Email,
MobileNo = customerBranchViewModel.MobileNo,
ContactNo = customerBranchViewModel.ContactNo,
Fax = customerBranchViewModel.Fax,
PrimaryAddress = customerBranchViewModel.PrimaryAddress,
City = customerBranchViewModel.City,
StateId = customerBranchViewModel.StateId,
CountryId = customerBranchViewModel.CountryId,
PinCode = customerBranchViewModel.PinCode,
CSTNo = customerBranchViewModel.CSTNo,
TINNo = customerBranchViewModel.TINNo,
PANNo = customerBranchViewModel.PANNo,
GSTNo = customerBranchViewModel.GSTNo,
AnnualTurnover = customerBranchViewModel.AnnualTurnover,
Status = true
};
responseOutBranch = dbInterface.AddEditCustomerBranch(customerBranch);
}
}
}
if (customerProducts != null && customerProducts.Count > 0)
{
foreach (CustomerProductViewModel customerProductViewModel in customerProducts)
{
CustomerProductMapping customerProduct = new CustomerProductMapping
{
CustomerId = customerId,
MappingId = customerProductViewModel.MappingId,
ProductId = customerProductViewModel.ProductId,
Status = true
};
responseOutProduct = dbInterface.AddEditCustomerProduct(customerProduct);
}
}
if(customerFollowUps!=null && customerFollowUps.Count>0)
{
foreach(CustomerFollowUpViewModel customerFollowUpViewModel in customerFollowUps)
{
CustomerFollowUp customerFollowUp = new CustomerFollowUp {

CustomerFollowUpId= customerFollowUpViewModel.CustomerFollowUpId,
CustomerId= customerId,
FollowUpActivityTypeId = customerFollowUpViewModel.FollowUpActivityTypeId,
FollowUpDueDateTime=Convert.ToDateTime(customerFollowUpViewModel.FollowUpDueDateTime),
FollowUpReminderDateTime= Convert.ToDateTime(customerFollowUpViewModel.FollowUpReminderDateTime),
FollowUpRemarks= customerFollowUpViewModel.FollowUpRemarks,
Priority= Convert.ToByte(customerFollowUpViewModel.Priority),
FollowUpStatusId= customerFollowUpViewModel.FollowUpStatusId,
FollowUpStatusReason= customerFollowUpViewModel.FollowUpStatusReason,
FollowUpByUserId= customerFollowUpViewModel.FollowUpByUserId,
CreatedBy= customerViewModel.CreatedBy,
CreatedDate=Convert.ToDateTime(customerFollowUpViewModel.CreatedDate)

};
responseOutFollowUp = dbInterface.AddEditCustomerFollowUp(customerFollowUp);
}

}

SL sl = new SL
{
SLId = 0,
SLCode = customerViewModel.CustomerCode,
SLHead = customerViewModel.CustomerName,
RefCode = customerViewModel.CustomerCode,
SLTypeId = 2,
CostCenterId = 0,
SubCostCenterId = 0,
CompanyId = customerViewModel.CompanyId,
CreatedBy = customerViewModel.CreatedBy,
Status = true
};

responseOutSL = dbInterface.AddEditCustomerSL(sl, customerViewModel.CustomerId == 0 ? “Add” : “Edit”);
transactionscope.Complete();
}
catch (TransactionException ex1)
{
transactionscope.Dispose();
responseOut.status = ActionStatus.Fail;
responseOut.message = ActionMessage.ApplicationException;
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex1);
throw ex1;
}
catch (Exception ex)
{
transactionscope.Dispose();
responseOut.status = ActionStatus.Fail;
responseOut.message = ActionMessage.ApplicationException;
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex);
throw ex;
}
}
return responseOut;

}

Role based security in MVC application

As the name says provide users to access pages by there access levels security.

Here we will implement role-based security by Action filters so the question is the what is action filters in MVC if you don’t know about the actions filters so will brief it first.

Action Filters: MVC provides a feature to users to allow the filters when an action will be executing or after an action will be executed.
Action filters have two events:

1.On Action Executing
2.On Action Executed

 

Now come to Role-Based Security:

Step-1: Here we have an example of activity calendar management in HR module, so we want to implement role-based security on it

Example: 

[ValidateRequest(true, UserInterfaceHelper.Add_Edit_ActivityCalender, (int)AccessMode.ViewAccess, (int)RequestMode.GetPost)]
public ActionResult AddEditActivityCalender(int activitycalenderId = 0, int accessMode = 3)
{

try
{
if (activitycalenderId != 0)
{

ViewData[“activitycalenderId”] = activitycalenderId;
ViewData[“accessMode”] = accessMode;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);
}
else
{
ViewData[“activitycalenderId”] = 0;
ViewData[“accessMode”] = 0;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);
}

}
catch (Exception ex)
{
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex);
}
return View();
}

Here we have an action method AddEditActivityCalender here we have to implement ValidateRequest Filter for implementing Role-Based Security.

Step-2: How ValidateRequest works here

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ValidateRequest : FilterAttribute, IAuthorizationFilter
{
public ValidateRequest();
public ValidateRequest(bool isActive, int userInterfaceId, int accessMode = 3, int requestMode = 1);

public void OnAuthorization(AuthorizationContext filterContext);
}

 

more : www.dotnethub.co.in