Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Data is Null. This method or property cannot be called on Null values

 Data is Null. This method or property cannot be called on Null values

Issue: 

Data is Null. This method or property cannot be called on Null values


Solution:

For columns that are nullable in your DB tables:

Wrong

 public string Memo { get; set; }

Correct: 

 public string? Memo { get; set; }


Hope this will help you and save your time.

Enjoy !!!

:)

Test discovery or execution might not work for this project

Error: Test discovery or execution might not work for this project.'


Issue

Message=Test discovery or execution might not work for this project. It's recommended to reference NuGet test adapters in each test project in the solution.

 

Solution

If you are using MS Test, try installing

MSTest.TestAdapter via nuget

if you are using nunit, install

NUnit3TestAdapter latest versions via nuget.

  
After installing please restart the visual studio and then you can see the tests running.

Hope this will help you and save your time.

Enjoy !!!

:)

Mock Unit Testing with Example

Mock Unit Testing with Example


Unit test cases should implement in our project, so as a developer we can assure that developed feature is working fine.

Here I have created a sample end to end.

DB Layer

//DB Layer: Database Class
public class tblUser
{
 public virtual string AddUser()
 {
  throw new NotImplementedException();
  //return "success";
 }
}
  

Business Layer

//Business Layer : Service Class
public class BLUser
{
 private readonly tblUser _BLUser;
 public BLUser(tblUser bLUser)
 {
  _BLUser = bLUser;
 }

 public string AddUser()
 {
  return _BLUser.AddUser();
 }
}
  

Implementation Layer

//Implementation Layer 
public class UserUI
{
 public string AddNew()
 {
  BLUser user = new BLUser(new tblUser());

  return user.AddUser();
 }
}
  

Test Project

//Unit Test: Test Class
[TestClass]
public class BLUserTest
{
 [TestMethod]
 public void AddUserTest()
 {
  var mockBLUser = new Mock<tblUser>();
  mockBLUser.Setup(mk => mk.AddUser()).Returns("success");
  var user = new BLUser(mockBLUser.Object);
  var actual = user.AddUser();
  Assert.AreEqual("success", actual);
 }  
}
   

Now you can do process on fileContent as per your requirement.

Hope this will help you and save your time.

Enjoy !!!

:)

How to add file in Resource file in C# ?

How to add file in Resource file in C# ?


We can add text or xml file in resource file in c# class library project.

Steps, how to use it.

 

Steps


1. Right click on project and select properties
2. Click on Resources option from left side
3. Click on link available in middle of the section, link as "This project does not contain a default resource file. Click here to create one."
4. Click on "Add Resource" from section menu and select "Add Existing File"
5. Select file from your file path
6. File is added in resource file
7. You can rename file name as per your requirement
  

Code

How to use file content in C# program

Add namespace 

using projectNameSpace.Properties;

byte[] file = Resources.FileName;
Stream stream = new MemoryStream(file);
string fileContent = "";

using (StreamReader reader = new StreamReader(stream))
{
     fileContent = reader.ReadToEnd();
}
  
Now you can do process on fileContent as per your requirement.


Hope this will help you and save your time.

Enjoy !!!

:)

Error: Inheritance security rules violated by type: 'System.Net.Http.WebRequestHandler'

Error: Inheritance security rules violated by type: 'System.Net.Http.WebRequestHandler'


Issue

Message=Inheritance security rules violated by type: 'System.Net.Http.WebRequestHandler'. Derived types must either match the security accessibility of the base type or be less accessible.

Source=Microsoft.Rest.ClientRuntime

Solution


I have updated nuget package "System.Net.Http" to version 4.3.1 with NuGet and that solved the issue.
  
Hope this will help you and save your time.

Enjoy !!!

:)

Explicit construction of entity type '###' in query is not allowed.

Explicit construction of entity type '###' in query is not allowed.


Issue

Explicit construction of entity type '###' in query is not allowed.

Solution


var result = from ev in db.Events
 join ea in db.EventAttendees on ev.EventId equals ea.EventId
 where ea.UserId == userid
 select new VMEvent // Here Don't use actual entity class name, Create new view model class
 {
  EventName = ev.EventName,
  EventAttendeeSubmittedDate = ea.SubmittedDate.ToString(),
  Place = ev.Place, 
  EventAttendeeNoofMembers = ea.noofMembers.ToString() 
  }; 

var arrayResult = result.ToArray();
var listResult = result.ToList();
 
  
Hope this will help you and save your time.

Enjoy !!!

:)

Date conversion issue

Date conversion issue



Solution


string strDate = "dd/MM/yyyy HH:mm:ss";

try
{
 dateTime = DateTime.ParseExact(strDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
catch
{
 dateTime = DateTime.ParseExact(strDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}

  

Hope this will help you and save your time.

Enjoy !!!

:)

IQueryable - Value cannot be null. Parameter name: property

Value cannot be null.

Parameter name: property


I got below error while I called orderby with IQueryable,

Error


Value cannot be null.
Parameter name: property

StackTrace:
.... OrderBy[T](IQueryable`1 query, String memberName, String direction) ....

I searched on many sites but did not get solution, then I start trial and run method on code. Finally I found that it was my silly mistake, 

Solution


SQL column name and what you passing in code should be same, its case sensitive

I was passing : countryName
SQL Column name: CountryName


Hope this will help you and save your time.

Enjoy !!!

:)

Get Time Zone list in C#

Get Time Zone list in C#


Here, it is a sample code to get time zone list in C#


string listTimeZone="";

foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones())
 listTimeZone += tzi.Id + " - " + tzi.DisplayName;




protected void Page_Load(object sender, EventArgs e)
        {
            var inputTime = Convert.ToDateTime("01/15/2019 04:30:00").ToUniversalTime();
 
            TimeZone localZone = TimeZone.CurrentTimeZone;

            lblMessage.Text = localZone.StandardName;

            DateTime outPutTime = inputTime.ToTimeZoneTime(localZone.StandardName);

            lblMessage.Text += "<br>" + inputTime.ToString();
            lblMessage.Text += "<br>India = " + outPutTime.ToString();


            lblMessage.Text += "<br>US Eastern Standard Time = " + inputTime.ToTimeZoneTime("US Eastern Standard Time").ToString();

        }



public static class genericDate
    {
        public static DateTime ToTimeZoneTime(this DateTime time, string timeZoneId = "Pacific Standard Time")
        {
            TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
            return TimeZoneInfo.ConvertTimeFromUtc(time, tzi); 
        } 
    }



Hope this will help you and save your time.

Enjoy !!!

:)

Convert Json to Class in C#

Convert Json to Class in C#


Here it is a sample code to convert json data into Class object.


namespace JsonToClass
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonInput = "{ username:'myName',password:'myPass'}";
 
            var data = JsonConvert.DeserializeObject<demo>(jsonInput);
        }
    }
 
    class demo
    {
        public string username { getset; }
        public string password { getset; }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

Read Event Viewer logs using C#

Read Event Viewer logs using C#


 Below demonstrated code helps to read logs data from event viewer and stores in database using entity framework.

Database table

CREATE TABLE [dbo].[EventLogData](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [EventId] [nvarchar](10) NULL,
 [EventType] [nvarchar](50) NULL,
 [Site] [nvarchar](200) NULL,
 [Source] [nvarchar](500) NULL,
 [TimeGenerated] [datetime] NULL,
 [Message] [ntext] NULL,
 CONSTRAINT [PK__EventLog__3214EC07A20289BA] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Code


namespace EventLogsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            EventLog log = new EventLog("Application");
            var entries = log.Entries.Cast<EventLogEntry>()
                                     // .Where(x => x.InstanceId == 4624)
                                     .Select(x => new
                                     {
                                         x.EventID,
                                         x.EntryType,
                                         x.Site,
                                         x.Source,
                                         x.TimeGenerated,
                                         x.Message
                                     })
                                      .ToList();

            List<EventLogData> eventLogDatas = new List<EventLogData>();
            EventLogData eventLogData;

            Console.WriteLine("Total Entries : " + entries.Count.ToString());
            foreach (var item in entries)
            {
                eventLogData = new EventLogData()
                {
                    EventId = Convert.ToString(item.EventID),
                    EventType = Convert.ToString(item.EntryType),
                    Site = Convert.ToString(item.Site),
                    Source = item.Source,
                    TimeGenerated = item.TimeGenerated,
                    Message = item.Message
                };
                eventLogDatas.Add(eventLogData);
            }

            using (var db = new EventsEntities())
            {
                db.Database.ExecuteSqlCommand("TRUNCATE TABLE EventLogData");

                db.EventLogDatas.AddRange(eventLogDatas);
                db.SaveChanges();
            }


            Console.WriteLine("Process completed. Press any key to continue...");
            Console.Read();
        }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

URL QueryString with Encryption & Decryption

URL QueryString with Encryption & Decryption

For the security concern we have to pass querystring value in encrypted mode,  and while we retrieve querystring value we need to decrypt it and use it.

Here, I mentioned..


  1. Plain text encryption
  2. Decryption of encrypted text
  3. URL encode (System.Web.HttpUtility.UrlEncode)
  4. URL decode (System.Web.HttpUtility.UrlDecode)

Here, I have mentioned URL querystring encryption and decryption...

Encryption

protected void Submit(object sender, EventArgs e)
    {
  string username = "anrorathod";
  string userid = "2279";
        string uname = HttpUtility.UrlEncode(Encrypt(username));
        string uid = HttpUtility.UrlEncode(Encrypt(userid));
        Response.Redirect(string.Format("~/newpagename.aspx?name={0}&id={1}", uname, uid));
    }

    private string Encrypt(string textToEncrypt)
    {
        string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
        byte[] clearBytes = Encoding.Unicode.GetBytes(textToEncrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                textToEncrypt = Convert.ToBase64String(ms.ToArray());
            }
        }
        return textToEncrypt;
    }


Decryption

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
   string username = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
   string userid = Decrypt(HttpUtility.UrlDecode(Request.QueryString["id"]));
        }
    }

    private string Decrypt(string textToDecrypt)
    {
        string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
        textToDecrypt = textToDecrypt.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(textToDecrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                textToDecrypt = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return textToDecrypt;
    }

Hope this will help you and save your time.

Enjoy !!!

:)

Code First Migration in ASP.Net Core

Code First Migration in ASP.Net Core

Generally we create database first and then we create data model classes in project, and while we publish application we need to take care about database creation and table.

Code first, its approach that we first create data model classes and code itself create database and while publishing application, we don't need to take care about database and its tables, code automatically manage.

While executing code first migration command in .Net Core C#, we are facing some issues sometimes, here I faced some issues and found some solutions as below.

Issue 1

Getting error, while executing command 

Add-Migration -Context "DatabaseContext" 

 Unable to create an object of type 'DatabaseContext'. Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

Solution 

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
{
 public DatabaseContext CreateDbContext(string[] args)
 {
  IConfigurationRoot configuration = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json")
   .Build();
  var builder = new DbContextOptionsBuilder<DatabaseContext>();
  var connectionString = configuration.GetConnectionString("dbConStr");
  builder.UseSqlServer(connectionString);
  return new DatabaseContext(builder.Options);
 }
}

Issue 2

Getting error, while executing below command

Add-Migration -Name "Migration Name" -Context "DatabaseContext"

GenericArguments[0], 'SampleWebAPI.Migrations.DatabaseContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.

Solution 

1. First remove migration folder (if any) from project which was created by above command

Issue 3

Getting error, while executing command 

Update-Database 

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

Solution 

Update-Database -Context "DatabaseContext"

Finally

Use below migration commands for .Net Core


1. Add-Migration -Name "Migration Name" -Context "DatabaseContext"

2. Update-Database -Context "DatabaseContext"



Enjoy !!!

:)

Code First Steps in ASP.Net C#

Code First Steps in ASP.Net C#

Generally we create database first and then we create data model classes in project, and while we publish application we need to take care about database creation and table.

Code first, its approach that we first create data model classes and code itself create database and while publishing application, we don't need to take care about database and its tables, code automatically manage.

Lets see, how to work with code first in .Net C#

Steps

1.First provide connection string in web.config file.
<connectionStrings>
    <add name="conDemoDB" connectionString="data source=ServerName; initial catalog=dbName; user id=username; password=password;" providerName="System.Data.EntityClient"/>
  </connectionStrings>

2. Create data model classes as per your requirement

3. Install Entity Framework using nu-get package installer or command 

4. Create DataContext Class

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
 
namespace DemoApp.Reporsitory
{
    public class dataContext : DbContext
    {
        public dataContext()
            : base("name=conDemoDB")
        {
        }
 
        public virtual DbSet<Menu> Menus { get; set; }
        public virtual DbSet<MenuItem> MenuItems { get; set; }
    }
}


5. Open Package Manager Console from Tools -> NuGet Package Manager

1. Enable-Migrations  

2. Add-Migration "Comments"

3. Update-Database -Verbose 

Once command executes successfully, you can open database and check that tables are created.

for more detail, https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/automatic

Enjoy !!!

:)

Consume web API in MVC or Windows Application or Console Application

Consume web API in MVC or Windows Application or Console Application

Sometime, we need to consume web API mostly in MVC or Windows Service or Windows Application or Console Application.  

Below code posts dynamic object in API call,


var url = "http://localhost/DemoWebAPIProject/api/ControllerName/Method";

Uri requestUri = new Uri(url);  
dynamic dynamicObject = new ExpandoObject();
dynamicObject.UserName = "anorathod".ToString();
dynamicObject.Password = "password";

string json = "";
json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicObject);

var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));

string responJsonText = await response.Content.ReadAsStringAsync()

I hope that this will helpful in your project.

Enjoy !!!

:)

DataTable : Add checkbox in jquery datatable and handle button event


DataTable : Add checkbox in jquery datatable and handle button event


How to add checkbox in jquery datatable and how to manage selected list on button click event. Solution is below,

HTML

 <fieldset class="clearfix fs-border">
            <legend class="fs-border">User's List:</legend>
            <div class="box-body">
                <table id="myTable" class="display responsive table table-striped dataTable no-footer" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th class="text-center"><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>Mobile</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                </table>
                <input type="button" id="btnSubmit" value="Submit Data" class="btn btn-default" />
            </div>
        </fieldset>

JQuery:

 var table = "";
var count = 0;
var totalCount = 0;
var checkedCount = 0;
 
$(document).ready(function () {
    $("#messagebox").hide();
    table = $("#myTable").DataTable({
        "processing"true,
        "serverSide"true,
        "filter"true,
        "orderMulti"false,
        "paging"true,
        "responsive"true,
        "ajax": {
            "type""POST",
            "url""ControllerName/GetJsonData",
            "dataSrc"function (data) {
                //Make your callback here.                
                if (data.value == "fail") {
                    window.location = "Unauthorised";
                } else {
                    //console.log(data);
                }
                countall(data.data);
                return data.data;
            }
        },
        "columnDefs": [{
            "targets": 0,
            "searchable"false,
            "orderable"false,
            "className""dt-body-center",
            "render"function (data, type, full, meta){
                return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
            }
        }],
        "order": [[1, "asc"]],
        "columns": [
            {
                data: null,
                orderable: false,
                width: 100,
                render: function (data, type, row) {
                    //console.log(data);
                    return "<input type='checkbox' id='" + data.userId + "'> "
                }
            },
               { "data""FirstName""name""FirstName" },
               { "data""LastName""name""LastName" },
               { "data""Email""name""Email" },
               { "data""Mobile""name""Mobile" },
               { "data""Status""name""Status" },
        ]
       
    });
 
    function countall(data)
    {
        totalCount =  data.length;        
    }
 
    // Handle click on "Select all" control
    $('#example-select-all').on('click'function () {
        // Get all rows with search applied
        var rows = table.rows({ 'search''applied' }).nodes();
        // Check/uncheck checkboxes for all rows in the table
        $('input[type="checkbox"]', rows).prop('checked'this.checked);
    });
 
    // Handle click on checkbox to set state of "Select all" control
    $('#myTable tbody').on('change''input[type="checkbox"]'function () {
        // If checkbox is not checked
        if (!this.checked) {
            var el = $('#example-select-all').get(0);
            // If "Select all" control is checked and has 'indeterminate' property
            if (el && el.checked && ('indeterminate' in el)) {
                // Set visual state of "Select all" controlas 'indeterminate'
                el.indeterminate = true;
            }
        }

      /// Set select all checkbox tick and untick
       checkedCount=0;
       table.$('input[type="checkbox"]').each(function () {
           if (this.checked) {                
               checkedCount++;               
               if(totalCount==checkedCount)
               {                    
                   $('#push-select-all').prop("indeterminate"false);
                   $('#push-select-all').prop('checked'true);
               }
           }            
       });

    });
 
 
    // Handle send event for selected users
    $('#btnSubmit').on('click'function (e) {
         
        var membersList = [];
            
        // Iterate over all checkboxes in the table
        table.$('input[type="checkbox"]').each(function () {        
            if (this.checked) {
                membersList.push({ userId: $(this).attr('id') });
                //console.log($(this).attr('id'));
                count++;
            }
        });
 
        if (count == 0)
        {
            alert("Please select atleast one user to submit data.");
        } 
        else {
            $.ajax({
                type: "POST",
                url: "ControllerName/ActionMethodName",
                contentType: 'application/json',             
                data: "{userList :" + JSON.stringify(membersList) + ",message :\"" + $("#Message").val() + "\"}",
                success: function (retdata) {                    
                    if (retdata == "success")
                        alert("Message sent successfully.");
                    else
                        alert(retdata);
                    
                }
            });
        }
       
    }); 
});

 

C# Code:

 [HttpPost]
        public JsonResult ActionMethodName(List<VMUsers> userList, string message)
        {
            var returnMessage = "business return message";
 
            return Json(returnMessage, JsonRequestBehavior.AllowGet);
        }
 
public class VMUsers
   {
       public string userId { getset; }
   } 


Enjoy !!!

 :)

ASP.Net, MVC - Get Client MAC ID


ASP.Net, MVC  - Get Client MAC ID



Below code gives client's mac id...

using System.Runtime.InteropServices;
 
namespace Demo.Common
{
    public class GetMACid
    {
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
 
        public static string getID()
        {
            string mac_dest = "";
            try
            {
                string userip = HttpContext.Current.Request.UserHostAddress;
                string strClientIP = HttpContext.Current.Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP);
                Int32 lhost = inet_addr("");
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }
 
               
 
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
            }
            catch (Exception err)
            {
                return err.Message;
            }
            return mac_dest;
        }
    }
}


Enjoy !!!

:)

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();