Linq Queries - Update data in query

Linq Queries - Update data in query



how to update an item in a list by linq

public static class UpdateExtensions
    {
        public delegate void Func<TArg0>(TArg0 element);

        public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> update)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (update == null) throw new ArgumentNullException("update");
            if (typeof(TSource).IsValueType)
                throw new NotSupportedException("value type elements are not supported by update.");

            int count = 0;
            foreach (TSource element in source)
            {
                update(element);
                count++;
            }
            return count;
        }
    }


Use update extension

var Datas = from ev in db.Events
                            join ea in db.EventAttendees on ev.EventId equals ea.EventId
                            where ea.UserId == userid
                            select new VMEvent
                            {
                                EventName = ev.EventName,
                                EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                                Place = ev.Place, 
                                EventAttendeeNoofMembers = ea.noofMembers.ToString() 
                             }; 
  var query = (from items in Datas
                             select items)
                          .Update(st => { st.EventDateString = st.EventDate.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);  });


Enjoy !!!
:)


Linq Queries


Linq Queries



Join and custom selected columns with some expression,

 var Datas = from ev in db.Events
                            join ea in db.EventAttendees on ev.EventId equals ea.EventId
                            join u in db.Users on ea.UserId equals u.UserId
                           // where ea.UserId == userid
                            select new VMEvent
                            {
                                EventName = ev.EventName,
                                EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                                Place = ev.Place,
                                EventDateString = ev.EventDate.ToString(),
                                EventAttendeeNoofMembers = ea.noofMembers.ToString(),
                                PricePerPerson = ev.PricePerPerson,
                                Total = (ev.PricePerPerson * ea.noofMembers).ToString()
                            };


Left outer join query:

 List<VMEvent> data = new List<VMEvent>();
var result = from ev in db.Events
                    join u in db.Users on ev.UserId equals u.UserId
                    join ea in db.EventAttendees on ev.EventId equals ea.EventId into Inners 
                    from od in Inners.DefaultIfEmpty()
                    where ev.EventDate >= startDate && ev.EventDate <= endDate
                    select new VMEvent
                    {
                        EventName = ev.EventName,
                        EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
                        Place = ev.Place,
                        EventDateString = ev.EventDate.ToString(),
                        EventAttendeeNoofMembers = ea.noofMembers.ToString(),
                        PricePerPerson = ev.PricePerPerson,
                        Total = (ev.PricePerPerson * ea.noofMembers).ToString(),
                        DivisionName = u.usertype
                    };
 data = result.Distinct().ToList();


JQuery DataTable

 

JQuery DataTable  


1. Datatable binding
2. Condition base show data
3. Delete popup 
4. Data refresh after deleted data


 HTML:

<table id="myTable" class="display responsive nowrap" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Event Date</th>
                        <th>Event Name</th>
                        <th>Place</th>
                        <th>Action</th>
                    </tr>
                </thead>
            </table>


//Delete Confirmation popup
<div class="modal fade" id="myModalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title title">Delete Confirm</h4>
                </div>
                <div class="form-horizontal formppup">
                    <div id="DeleteDiv"></div>
                </div>
                <div class="form-horizontal formppup" align="center">
                    <input type="button" id="ConfirmDeleting" class="btn btn-primary" value="Yes" />
                    <input type="button" value="No" data-dismiss="modal" class="btn btn-default" />
                </div>
            </div>
        </div>
    </div>

 

 JQuery:

var table = "";
$(document).ready(function () {
    table = $("#myTable").DataTable({
        //Condition base show data
        //columnDefs : [
        //{ targets : [3],
        //    render : function (data, type, row) {
        //        return data == '12' ? 'free' : 'paid'
        //    }
        //}],
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "paging": true,
        "responsive": true,
        "ajax": {
            "type": "POST",
            "url": "EventMaster/GetJsonData",
            "dataSrc": function (data) {
                //Make your callback here.                
                if (data.value == "fail") {
                    window.location = "Unauthorised";
                } else {
                    console.log(data);
                }
                return data.data;
            }
        },
        "columns": [
                { "data": "EventDate", "name": "EventDate" },
                { "data": "EventName", "name": "EventName" }, 
                { "data": "Place", "name": "Place" }, 
                {
                    data: null,
                    orderable: false,
                    width: 100,
                    render: function (data, type, row) {
                        //console.log(data);
                        return "<a href='EventMaster/Edit/" + data.EventId + "' class='fa-icon edit' ><i class='fa fa-pencil'></i></a>"
                                + "&nbsp;<a id=" + data.EventId + " class='fa-icon delete' Onclick='fnConfirm(this);' ><i class='fa fa-trash-o'></i></a>"
                    }
                }
        ]
    });
});


function fnConfirm(model) {
    $('#myModalDelete').modal('show');
    $("#DeleteDiv").html("Are you sure you want to delete this record?");
    $("#ConfirmDeleting").click(function () {
        $.ajax({
            url: "EventMaster/DeleteData/" + model.id,
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            data: $(this).serialize(),
            success: function (data, textStatus, jQxhr) {
                $('#myModalDelete').modal('hide');
                table.ajax.reload(null, false);
            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    });
}


 

Enjoy !!!

:) 

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

:)