ASP.Net - MVC C# | Report : Microsoft Reporting - Implement RDLC in MVC

 

ASP.Net - MVC C#| Report : Microsoft Reporting

- Implement RDLC in MVC



Here, I have demonstrate, how to implement Microsoft reporting in MVC web application. Please follow below steps to achieve reporting.

Step1 : Create web application with blank and select code reference "MVC". I have created project name with "DemoReport".

Step 2: Add empty controller name what you want. I have create "Home" and "Country".

Step 3: Add Entity Data Model follow screenshots.













Step 4: Add below code in Index action of Country controller
public ActionResult Index()
        {
            List<Country> countryList = null;
 
            using (DemoReportEntities db = new DemoReportEntities())
            {
 
                countryList = db.Countries.OrderBy(o=>o.CountryName).Take(10).ToList();
            }
            return View(countryList);
        }

fda


Step 5: Add below html code in Index view of Country
@model IEnumerable<DemoReport.Models.Country>
@{
    ViewBag.Title = "Country";
}
 
<div class="box">
    <div class="box-header with-border">
        <h3 class="box-title">Country List</h3>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="box-body">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <th>Country Name</th>
                            <th>Country Code</th>
                        </tr>
                        @foreach (var item in Model)
                        {
                            <tr>
                                <td>@Html.DisplayFor(m => item.CountryName)</td>
                                <td>
                                    @Html.DisplayFor(m => item.CountryCode)
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col-md-6">
            <div><a href="@Url.Action("GenerateReport",new {id= "PDF"})" class="btn btn-primary btn-Report"> Get Report PDF</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Excel"})" class="btn btn-primary btn-Report"> Get Report Excel</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Word"})" class="btn btn-primary btn-Report"> Get Report Word</a></div>
            <div><a href="@Url.Action("GenerateReport",new {id= "Image"})" class="btn btn-primary btn-Report"> Get Report Image</a></div>
        </div>
    </div>
</div>

 Step 6: Add css class in site.css or your stylesheet.
.btn.btn-primary.btn-Report {width:150px !importantmargin:3px


Step 7: Add below html code in _Layout.cshtml for menu option
<div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>
                        @Html.ActionLink("Country List""Index""Country"new { area = "" }, new { @class = "navbar-brand" })
                    </li>
                </ul>
            </div>


Step 8: Run application and it will give output as below,

 

Step 9: Add new folder in project for report, I added "Reports", then follow  below steps



 
Step 10: Add new folder in project for report data sets, I added "ReportDataSet", then follow  below steps














Step 11: Add data set to Report,




 
Step 12: Add header and footer in report


 
Step 13: Add report assembly reference in project.

Step 14: Lastly write code to generate report file in pdf, word, excel or image. create new action method in country controller and write below code.

public ActionResult GenerateReport(string id)
        {
            List<Country> data = null;
            using (DemoReportEntities db = new DemoReportEntities()){
                data = db.Countries.OrderBy(o => o.CountryName).Take(10).ToList();
            }
 
            LocalReport lr = new LocalReport();
            string path = Path.Combine(Server.MapPath("~/Reports"), "CountryReport.rdlc");
            if (System.IO.File.Exists(path)){
                lr.ReportPath = path;
            }
            else{
                return View("Index", data);
            }
 
            ReportDataSource rd = new ReportDataSource("ReportCountryDataSet", data);
            lr.DataSources.Add(rd);
            string reportType = id;
            string mimeType, encoding, fileNameExtension;
            
            string deviceInfo = "<DeviceInfo> <OutputFormat>" + id + "</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth> <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop> <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight> <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";
 
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
 
            renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, 
                out fileNameExtension, out streams, out warnings);
 
            return File(renderedBytes, mimeType);
        }

Step 15: Finally run the project and click on Generate Report button. See generated pdf.


I hope that you like the reporting tutorial.

Enjoy !!!

:)

 

 


ASP.Net - MVC C#| Error: The required anti-forgery form field "__RequestVerificationToken" is not present.

 

ASP.Net - MVC C#| Error: The required anti-forgery form field "__RequestVerificationToken" is not present.

I am using Membership.create user function, then the following error is occurring,
 
The required anti-forgery form field "__RequestVerificationToken" is not present.

How can I fix this?

Solution: 

 You have [ValidateAntiForgeryToken] attribute before your action. You also should add @Html.AntiForgeryToken() in your form.

 

Enjoy !!!

:) 

ASP.Net - MVC C#| Error : A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was not present on the provided ClaimsIdentity.


ASP.Net - MVC C#| Error : A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was not present on the provided ClaimsIdentity.


How to get enum description text, here is the code to achieve this.

Error:

A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier.

Set below code in global.cs to get exact error of claim.

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

Actual error of claim:

A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was not present on the provided ClaimsIdentity.

Solution:

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "username"),
    new Claim(ClaimTypes.Email, "user@gmail.com"),
    new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid
};

Enjoy !!!

:)

 

ASP.Net, MVC C#| Get Enum Description Text


  ASP.Net - MVC C#| Get Enum Description Text


How to get enum description text, here is the code to achieve this.

Enum Code :

public enum TaskList
   {
       [Description("Open")]
       Open = 1,
       [Description("Work In Progress")]
       WIP = 2,
       [Description("Pending")]
       Pending = 3,
       [Description("Closed")]
       Closed = 4
   }

Code for get description:

using System.Reflection;
 
public class EnumList
    {
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();
 
            MemberInfo[] memInfo = type.GetMember(en.ToString());
 
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
 
                if (attrs != null && attrs.Length > 0)
                {
                    return ((System.ComponentModel.DescriptionAttribute)attrs[0]).Description;
                }
            }
 
            return en.ToString();
        }
    }

Code :

var taskList = from TaskList task in Enum.GetValues(typeof(TaskList))
                             select new
                             {
                                 ID = (int)task,
                                 Name = EnumList.GetDescription(task),
                                 Text = task.ToString()
                             };
 
            // To bind dropdown
            ViewBag.taskStatus = new SelectList(taskStatus, "ID""Name""tasks");
 
            // for sample how it works
            string strList = "";
            foreach (var item in taskList)
            {
                strList += item.Text + "  ";
            }

HTML :

@Html.DropDownList("taskid", (SelectList)ViewBag.taskStatus)

Enjoy !!!

:)

ASP.Net C#| Download File


  ASP.Net C#| Download File



Code - Method 1:

try
            {
                string strURL = "/Files/filename.pdf";
                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition""attachment;filename=\"" + strURL + "\"");
                byte[] data = req.DownloadData(Server.MapPath(strURL));
                response.BinaryWrite(data);
                response.End();
            }
            catch (Exception ex)
            {
            }

Code - Method 2:

try
            {
                Response.ContentType = "Application/pdf";
           Response.AppendHeader("Content-Disposition""attachment; filename=TechnicalDocumentforLogin.pdf");
           Response.TransmitFile(Server.MapPath("~/Files/filename.pdf"));
           Response.End();
            }
            catch (Exception ex)
            {
            }

  Enjoy !!!

:)

 

ASP.Net C#| Send Email


  ASP.Net C#| Send Email


Here I write a code to send email and its 100% working if you pass correct value.

HTML:

<div class="container">
       <div style="min-height30px">
           <label id="lblMessage" runat="server"></label>
       </div>
       <div class="row">
           <div class="col-md-6">
 
               <div class="form-group">
                   <label>SMTP:</label>
                   <asp:TextBox ID="txtSMTP" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Port:</label>
                   <asp:TextBox ID="txtPort" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Username</label>
                   <asp:TextBox ID="txtUsername" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Password</label>
                   <asp:TextBox ID="txtPassword" runat="server" TextMode="password" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>SSL Enable</label>
                   <asp:CheckBox ID="chkSSL" runat="server"></asp:CheckBox>
               </div>
           </div>
           <div class="col-md-6">
               <div class="form-group">
                   <label>From:</label>
                   <asp:TextBox ID="txtFrom" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Display Name:</label>
                   <asp:TextBox ID="txtFromDisplay" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>To:</label>
                   <asp:TextBox ID="txtTo" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Subject:</label>
                   <asp:TextBox ID="txtSubject" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Body:</label>
                   <asp:TextBox ID="txtBody" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="btn btn-success" />
               </div>
           </div>
       </div>
   </div>

Code:

using System;
using System.Net;
using System.Net.Mail; 
protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                var mailmessage = new MailMessage { From = new MailAddress(txtFrom.Text.Trim(), txtFromDisplay.Text.Trim()) };
 
                mailmessage.To.Add(txtTo.Text.Trim());
                mailmessage.Subject = txtSubject.Text.Trim();
                mailmessage.Body = txtBody.Text.Trim();
                mailmessage.IsBodyHtml = true;
 
                SmtpClient smtpClient = null;
                smtpClient = new SmtpClient();
 
                smtpClient.Host = txtSMTP.Text.Trim();
                smtpClient.Port = Convert.ToInt32(txtPort.Text.Trim());
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;                
                smtpClient.Credentials = new NetworkCredential(txtUsername.Text.Trim(), txtPassword.Text.Trim());
 
                if (chkSSL.Checked)
                    smtpClient.EnableSsl = true;
                else
                    smtpClient.EnableSsl = true;
 
                smtpClient.Send(mailmessage);
                lblMessage.InnerText = "Email sent.";
            }
            catch (Exception ex)
            {
                lblMessage.InnerText = ex.Message;
            }
        }
 
        public static string GenerateRandomString(int length)
        {
            //It will generate string with combination of small,capital letters and numbers
            char[] charArr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
            string randomString = string.Empty;
            Random objRandom = new Random();
            for (int i = 0; i < length; i++)
            {
                //Don't Allow Repetation of Characters
                int x = objRandom.Next(1, charArr.Length);
                if (!randomString.Contains(charArr.GetValue(x).ToString()))
                    randomString += charArr.GetValue(x);
                else
                    i--;
            }
            return randomString;
        }

Method 2

 using (MailMessage email = new MailMessage())
                {
                    email.From = new MailAddress(contact.Email);
                    email.To.Add(toEmail);
                    email.Subject = "Hello World";
                    email.Body = "<h1>Hello</h1>";
                    email.IsBodyHtml = true;
                   email.Attachments.Add(new Attachment("C:\\file.zip"));

                    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                    {
                        smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["fromUserName"], password);
                        smtp.EnableSsl = true;
                        smtp.Send(email);
                    }
                }

After 2024

Follow the steps mentioned https://mailtrap.io/blog/gmail-smtp/


Enjoy !!!

:)