Working With Multiple Models In A Single View - ASP.NET MVC

Download Sample Source Code-Using Multiple Models In Single View ASP.NET_MVC_5.zip Introduction Most of the real work application requires to show data from multiple/different Models / Tables / Databases. Showing multiple models in a view is common requirement, that's where I started Learning different ways to achieve this. Best approaches of passing / using multiple models (objects)in one view in ASP.NETMVC 4 / MVC 5 are as follows: Using Combined Model (Model with multiple objects) Using Partial Views Using Ajax Data Carrier in MVC ViewBag ViewData TempDataBackground Please download sample c...

Working With Files In ASP.NET MVC : File Operations

Uploading, Downloading, Displaying / Streaming and DeletingMultiple Files in ASP.NET MVC (C#): Download Sample Source Code - Working With Files ASP.NET MVC 5 File processing- Working with Files (Uploading / Downloading / Displaying Streaming / Deleting) using C# in ASP.NET MVC 4 and MVC 5 , here we are going to cover following : Setting up form method and content type Uploading Files Uploading File On Server Uploading Multiple Files On Server Downloading Files Streaming / Displaying Files Deleting Files This article will work for all types of files- Images / Videos ( .jpg, .png, .bmp, .jpeg, ....

Html.ActionLink As Button Or An Image, Not A Link

Apply a CSS class to the htmlAttributes object. <%= Html.ActionLink("Button Name", "Action Name", "ControllerName", new { @class="classname" }) %> and then create a class in your stylesheet a.classname { background: url(../Images/image.gif) no-repeat top left; display: block; width: 150px; height: 150px; text-indent: -9999px; /* hides the link text */ }...

Exception Handling in ASP.NET MVC Web Application

ASP.NET MVC Error handling using CSharp: Exception handling is crucial part of every application. It is required for logging errors into database or text/log file, very importantly presenting them to the user in a nicely in case of exception. Introduction: When I was working on application I encounter exceptions (e.g. 400, 500, etc ) but I was not sure of what might have caused it. That's where I started exploring various approaches of exception handling in ASP.NET MVC. There are various ways to handle exceptions, based upon usability and error location/type (SQL, Application, etc) We are goin...

Working With Exchange Server Using Web Service (EWS)

Introduction Remotely working with Exchange Server /Outlook using Exchange Web Service (EWS)- There are many article how to process using EWS managed API but there are very less article of how we can actually do it remotely using exchange web service. EWS Managed API works only on exchange server. If you are looking for remote processing here is solution. Following are steps involved - Creating An Instance Of Exchange Web Service (EWS) Process Unread Email Attachment Iterate Through Attachments Process Email Attachments Change Status of Emails From ‘Unread’ to ‘Read’How It Works/Using Code : C...

Adding / Updating Meta Tags Dynamically In ASP.NET MVC 4 / MVC 5

If you are working in ASP.NET MVC have questions like -How to pass page's meta tags - adding Meta tags onRazor engine.cshtml Pages/adding it dynamically ? Here is answer-In this article we are going to see three ways of doing this- Using JQuery Using ViewBag Using @RenderSection and @Section Approach 1 - Using Jquery : A) In the "_Layout.cshtml" page add a new section call inside the <head> tag, as given below: <head> <meta name="keywords" content="" /> <meta name="description" content="" /> </head> B) In Page/View ( e.g Index )add following Script : Approach 2 - ...

How to get list of all active Sessions in ASP.NET MVC?

Download Free Source Code Sample :List_Active_Sessions_In_ASP_NET_Web_Form_MVC.zip Introduction In this article we are going to see how can we can we track active users in ASP.NET (Web Form & MVC) web application, and to answer questions like How to get online users count? Track/get active user information? etc. We are going to do it in four steps: Creating Session Repository Setting web.config Configuration Storing Session Data Removing Session Data Show Online User (Active Sessions) CountBackground Please download sample code so that you can follow code along with documentation. Sample c...

FIX-The Length Of The URL For This Request Exceeds MaxUrlLength

FIX : [HttpException (0x80004005)]: The length of the URL for this request exceeds the configured maxUrlLength value. (HTTP/1.1 400 Bad Request)-What is default length of QueryString / GET / URL parameters?Default length is 290 characters.What is the maximum limit on QueryString / GET/ POST / URL parameters /length?Maximum uniform resource locator (URL) length is 2,083 characters. This limit applies to both POST and GET request URLs.Note – Maximum URL also varies based on browsers.e.g. On Windows:· Opera supports ~4050 characters,· IE 4.0+ supports exactly 2083 characters,· Netscape 3 -> 4....

Changing Status Of Emails Using Exchange Web Service (EWS)

Changing status of emails from ‘unread’ to ‘read’ using Exchange web service (EWS)- In previous article (How to process email attachments using Exchange web service in ASP.NET?) we saw how to iterate through attachment and process them. Once it is processed you would like to mark as read (change status from ‘unread’ to ‘read’ )Here will se how we can do that. /// <summary> /// EWS code to update the IsRead flag, *ONLY* for MessageType /// </summary> /// <param name="messageId">email massage/item id</param> /// <returns>boolean value true- if it marked as read else...


FIX-A Potentially Dangerous Request Was Detected From The Client

ASP.NET MVC-A potentially dangerous Request was detected from the clientException Details: System.Web.HttpRequestValidationException: [HttpRequestValidationException (0x80004005)A potentially dangerous Request.Form value was detected from the client (Model_Field="<!-- Begin ...")Source Error :An unhanded exception was generated during the execution of the current web request.Information regarding the origin and location of the exception can be identified using the exception stack trace below.Description: ASP.NETMVC has detected data in the request that is potentially dangerous because it mi...

ASP.NET MVC Searching in Table Using JQuery - Client Side

Download Source Code - Searching In Table ASP.NET MVC 5 In this approach we are assuming we have all data loaded on page. If there are many rows and columns we would like to provide search functionality. Here we are going to create UI just as shown- For this you need - <p> Search term: <input type="text" name="search" /> </p> <table cellpadding="0" cellspacing="0" border="2"> <tr class="data-header" style="color:Blue;"> <td> JQuery Searching - Text 1 </td> <td> JQuery Searching - Text 2 </td> </tr> <tr class="data-row"> <td&g...

ASP.NET MVC File Upload On Server : File Operations

Download Sample Source Code - Working With Files ASP_NET MVC 5 We have seen how to post files (ASP.NET MVC Working With Files - Setting up form method and content type), files will be available in post method defined in controller. Using Request.Files and HttpPostedFile we are going to upload using following code.This is generic code, will work with uploading multiple files (if multiple files are posted) public class HomeController : Controller{ [HttpPost] public ActionResult UploadFile() { foreach (int i = 0; i < Request.Files.Count; i++){ HttpPostedFileBase hpf = Request.Files[file]; if (...

ASP.NET MVC Uploading Multiple Files On Server

Download Sample Source Code - Working With Files ASP_NET MVC 5 Now that we have see how to post file and how to upload file on server. ASP.NET MVC Working With Files - Setting up form method and content type (Post Files)ASP.NET MVC Working With Files - Uploading File On ServerIn order to upload multiple file you just need to add input control in view of type=”file”.View - @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){ <input type="file" name="FileUpload1" multiple/><br /> <input type="submit" name="Submit" id="Submit" value="...

Creating An Instance Of Exchange Web Service In ASP.NET

Creating an instance of Exchange web service (EWS) in ASP.NET (MVC) using CSharp: First you will need to add web service to project then you will get instance of ExchangeServiceBinding() . You can initiate/invoke an instance of EWS using following code : /// <summary> /// Set all required configuration parameters /// </summary> public void Initialize() { try { // you can also get if from configuration file EmailAddress = "MyEmail@MyDomain.Com"; //AppConfig.EmailAddress; UserName = "MyUserName"; //AppConfig.UserName; Password = "MyPassword"; //AppConfig.Password; Domain = "myDomain"...

Using A JQuery UI Modal Form In ASP.NET MVC List Page

Lets say I have:$(document).ready(function() { $(“#dialog”).dialog(); $(“#dialog”).dialog(‘close’); $(‘.myPop’).click(function() { $(“#dialog”).dialog(‘open’); }); }); Which allows me to pop-up on the click of ‘.myPop’ which is just a temp input button in my list which is working: My question is – what is the best way to use this pop-up to go to the Edit method of my controller, populate controls and then be able to save back to the model and refresh the list page? There’s obviously a bunch of ways to do that, but here’s how I would solve it. Perform an Ajax call before loading the dialog to p...

Preventing JavaScript Injection Attacks In ASP.NET MVC

ASP.NET MVC Preventing JavaScript Injection Attacks- There are two ways to do this -1) Using HTML Encode in view2) Using Html Encode in controller Approach #1: HTML Encode in the View @{ Html.Encode(Model.Value) } Approach #2: HTML Encode in the Controller -Code behind public ActionResult Create(string value) { var newModel = new Model(); newModel.Value = Server.HtmlEncode(value); db.Model.InsertOnSubmit(newModel); db.SubmitChanges(); return RedirectToAction("Index"); } ...

Setting Up Form Method And Content Type In ASP.NET MVC

In Web Forms, when you drag a FileUpload control on to the designer, html form that wraps the entire page is decorated with an extra attribute: enctype="multipart/form-data" and method=”post”. method=”post” - is needed because the form by default will be submitted via the HTTP get method.enctype="multipart/form-data" - is needed to post form in multiple parts.The FileUpload itself is rendered as an html input type=file. Within an MVC View, there are a number of ways to set this up. The first is with HTML:<form action="/Home/UploadFile" method="post" enctype="multipart/form-data"> <inp...

FIX-The Length Of The String Exceeds Max Json Length Property

HTTP 500 - The length of the string exceeds the value set on the maxJsonLength property-500 Internal Server Error : Error Message :"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."ExceptionType : "System.InvalidOperationException"Stack Trace : " at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationForma...

Processing Email Attachments Using Exchange Web Service (EWS)

In previous article (How to iterate through the attachments using Exchange web service in ASP.NET?) we saw how to iterate through attachments contained in unread email and filtering based on type. I applied filter to process only attachment of xml type.Here will see how we can process xml file in outlook email. /// <summary> /// Here is code to process attachement /// </summary> /// <param name="esb"></param> /// <param name="itemID"></param> private static void ProcessAttachmentByAttachmentItemID(ExchangeServiceBinding esb, string itemID) { // Create the re...


Search Text In All Definitions Of SQL Objects

Searching text in SQL database objects - Stored Procedures (SP), Views, Triggers, Tables-Here is list of all SQL Objects :For reference I have used ‘AdventureWroks’ database and here I have created Stored procedure to give me all SQL objects using search text.you can also apply filter based on USE AdventureWorksGO ALTER PROCEDURE [dbo].[FindTextInDatabaseObjects] @SearchText VARCHAR(255) AS BEGIN SELECT DISTINCT o.name AS Object_Name, o.type_desc as Object_Type, @SearchText SearchCriteria FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o.object_id WHERE m.definition LIKE '%' +...

Invoke Action Method With Parameters In ASP.NET MVC

Making an html button call an action method with parameters in ASP.NET MVC using CSharp- A) If Action Type is GET <input type="button" value="Index" onclick="location.href='<%: Url.Action("Index?queryString=value") %>'" /> B) If Action Type is POST Add submit button and and in controller post action access parameter as : public ActionResult CCDReview([DefaultValue(1) int CUrrentPage], string paramString) { //method code is here. } ...

Exception Handling at Application Level - Using Global.aspx

In previous post you have seen how we can handle exception inside action method Exception Handling in ASP.NET MVC - Using Action MethodAdvantage - custom error handling can be done for particular action method.Disadvantage - We need to repeat code (try… catch block) in every action.That's why it is good to handle exceptions at application level, so that will write code once use it for all pages.In order to do that you have to add Application_Error() function definition in Global.aspx as follows, this is just an example.protected void Application_Error() { Exception unhandledException = Server....

Exception Handling at Page (View) Level - Using Action Method

Will discuss different exception handling mechanisms that will fit to an MVC application - First will start with handling inside Action method.IntroductionException handling is crucial part of every application. It is required for logging errors into database or text/log file, very importantly presenting them to the user in a nicely in case of exception.When I was working on application I encounter exceptions (e.g. 400, 500 ) but I was not sure of what might have caused it. Thats where I started exploring various approaches of exception handling in ASP.NET MVC.In this article we are going to s...

Processing Unread Email Attachment Using Exchange Web Service

Processing unread email attachment using Exchange web service CSharp:In ASP.NET you would first need to instantiate Exchange Web Service (EWS) and then apply filter to process through folder and other filter criteria.Here is sample code you can use : public void ProcessUnReadEmailAttachments() { try { //Set all requred configuration parameters this.Initialize(); //Click here for - how to create/initiate an instance of Exchange web service (EWS) in ASP.NET? FindItemType findItemRequest = new FindItemType(); // Setup the mailbox using the smtp address of the account wanted var mailbox = new Emai...

FIX-Msg:3702 Cannot Drop Database Because It Is Currently In Use

Database currently in use-Msg 3702, Level 16, State 3, Line 2 Cannot drop/detach database “DataBaseName” because it is currently in use.The common mistake user is kept the connection open with this database and trying to drop the database. The following commands will raise above error: USE AdventureWorks; GO DROP DATABASE AdventureWorks; GO Fix/Workaround/Solution: The following commands will not raise an error and successfully drop the database: USE Master; GO DROP DATABASE AdventureWorks; GO If you want to drop the database use master database first and then drop the database.If you are stil...

Connecting Outlook Using Exchange Web Service ASP.NET

Connecting outlook using exchange web service ASP.NET (MVC)- first you will need to add web service to project then you will get instance of ExchangeServiceBinding()Following code will help you : ExchangeServiceBinding esb = new ExchangeServiceBinding(); esb.RequestServerVersionValue = new RequestServerVersion(); esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1; esb.Credentials = new NetworkCredential("", "", ""); esb.Url = @"https:///ews/Exchange.asmx"; ...

Iterating Email Attachments Using Exchange web service (EWS)

In previous article (How to process unread email attachment using Exchange web service in ASP.NET?) we saw how to iterate through unread emails and process data, now here we are going to see how to iterate through the attachments of email.for that we are going to use following code block where we are going to pass instance of Exchange Service binding and item ID of email. /// <summary> /// Get all items associated with email /// </summary> /// <param name="binding"></param> /// <param name="itemID"></param> public void GetAttachmentsByItemID(ExchangeServiceB...

Difference Between Vidya and Shiksha

Guru is one who gives vidya.Shikshak gives shiksha.Vidya teaches morality, values, difference between good and bad etc.Shiksha teaches subjects meaning Math, Sciences, Languages, and Social Sciences etc.The Guru also taught how to lead a life with dharma (virtues)....

Import Data From Excel To Sql (Data Migration) In ASP.NET

Download Sample Code- Data Upload From Excel To SQL Using CSharp Excel To SQL Data Upload - Introduction Please download attached sample code -Download Sample Code- Data Upload From Excel To SQL Using CSharp. In this article we are going to see how to upload data from excel to page and SQL with working example. We have employee data stored in ‘EmployeeMaster.xlsx’ file stored in ‘App_Data’ folder which we are going to load on page and save into database. Excel Connection String string filePath = Request.PhysicalApplicationPath + @"\App_Data\EmployeeMaster.xlsx"; //create excel connection strin...

Sending Email from SQL Server Integration Services (SSIS)

Sending email notification is crucial part of every business, most of time based upon business requirement. Here we are going to see how we can do that using SQL Server (SSIS package).IntroductionCreating Source For NotificationIterate Through Each RecordSend EmailCreating Source For NotificationWill create view as our source data for notification to get fields required for notificatione.g. View name - NOTIFICATION_SOURCEFields :EMAIL_FROMEMAIL_TOEMAIL_SUBJECTEMAIL_BODYCreate variable which will be used as instanstance of each row. It should be of type ObjectSet source of Execute SQL Task as N...