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 !!!

:)

 

ASP.Net Webform | Show progress image on page load



ASP.Net Webform | Show progress image on page load


Sometime we need to show loader image before page load on user interface. Here below is the code to implement this.

HTML:

<div>
           <asp:Button ID="btnLoad" runat="server" Text="Load Country" OnClick="btnLoad_Click" />
</div>
        <div>
            <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="CountryName" HeaderText="Country Name" />
                    <asp:BoundField DataField="CountryCode" HeaderText="Country Code" />                    
                </Columns>
            </asp:GridView>

            <div class="loading" align="center">
                Please wait ! Page loading...<br />
                <br />
                <img src="Images/loader.gif" />
                
            </div>
        </div>

 

CSS:

<style type="text/css">
    .modal
    {
        positionfixed;
        top0;
        left0;
        background-colorblack;
        z-index99;
        opacity0.8;
        filteralpha(opacity=80);
        -moz-opacity0.8;
        min-height100%;
        width100%;
    }
    .loading
    {
        font-familyArial;
        font-size10pt;
        border5px solid #67CFF5;
        width200px;
        height100px;
        displaynone;
        positionfixed;
        background-colorWhite;
        z-index999;
    }
</style>

 

JS:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 
<script type="text/javascript">
    function ShowProgress() {
        setTimeout(function () {
            var modal = $('<div />');
            modal.addClass("modal");
            $('body').append(modal);
            var loading = $(".loading");
            loading.show();
            var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
            var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
            loading.css({ top: top, left: left });
        }, 200);
    }
    $('form').live("submit"function () {
        ShowProgress();
    });
</script>

 

Code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string script = "$(document).ready(function () { $('[id*=btnLoad]').click(); });";
                ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
            }
        }
 
        protected void btnLoad_Click(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
 
            string strConnString = ConfigurationManager.ConnectionStrings["constrDemo"].ConnectionString;
            string query = "SELECT * FROM Country";
            SqlCommand cmd = new SqlCommand(query);
            
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds, "Customers");
                        gvCustomers.DataSource = ds;
                        gvCustomers.DataBind();
                    }
                }
            }
            btnLoad.Visible = false;
        }

 

Configuration:

<connectionStrings>
 <add name="constrDemo" connectionString="Data Source=servername;Initial Catalog=datbasename;User id =dbusername;password=dbpassword" />
</connectionStrings>

 Enjoy !!! 

:)

Entityframework | DbEntityValidationException Validation failed for one or more entities



Entityframework | DbEntityValidationException

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities


Resolved entity framework db entity validation exception.

Code:

catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage); 
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }

Another way....

catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                var fail = new Exception(msg, dbEx);                
                throw fail;
            }

  Enjoy !!!

  :)