Displaying a Calculated Column in DynamicData Site table? - calculated-columns

According to what I've read, to add a calculated Column to display in the ASP DynamicData table, I just need to add a Readonly property to the table class, and set: [ScaffoldColumn(true)] and return the value.
Here's what I did according to those rules, and it does not work:
public struct Rep
{
public int ID;
public string Name;
}
[ScaffoldTable(true)]
public partial class RepInfo
{
private static bool IsGotAllReps = false;
public static List<Rep> Reps
{
get
{
IQueryable<int> srID = null;
IQueryable<Rep> srName = null;
if (!IsGotAllReps)
{
using (MiscDataContext dc = new MiscDataContext())
{
srID = dc.MdmSalesAdjustment.Select(s => s.RepID).Distinct();
}
using (DWDataContext dc = new DWDataContext())
{
srName = dc.ReportHierarchy.Select(s => new Rep { ID = s.RepEmployeeID, Name = s.RepFirstName + " " + s.RepLastName }).Distinct();
}
}
IsGotAllReps = true;
return srID.Join(srName, id => id, name => name.ID, (id, name) => new Rep { ID = name.ID, Name = name.Name }).ToList();
}
}
//THIS IS AN EXISTING COLUMN IN THE TABLE THAT I WILL USE TO GET THE REPNAME - SEEL CALC COL BELOW
public virtual int RepID
{
get;
set;
}
//THIS IS THE CALCULATED COLUMN THAT I WANT TO SHOW.
[ScaffoldColumn(true)]
public virtual string RepName
{
get
{
return Reps.Where(r => r.ID == this.RepID).FirstOrDefault().Name;
}
}
}
Everything still works, table displays as expected, it's just that I'm not seeing the calculated column.
Thanks!

Related

AutoMapper 10.0.0 with F# - How to fix it without additional mapping?

I have 3 types :
type [<CLIMutable>] status = { id : Guid; name : string }
type [<CLIMutable>] container = { id : Guid; name : string; status : status}
type [<CLIMutable>] scontainer = { id : Guid; name : string; status : string}
and next configuration
let c =
MapperConfiguration(
fun config ->
config.CreateMap<container, scontainer>()
.ForMemberFs((fun sc -> sc.name), (fun opts -> opts.MapFrom(fun m _ -> m.status.name))) |> ignore
)
I'm trying to map with next code
let con = { id = Guid.NewGuid(); name = "Template 1"; container.status = { id = Guid.NewGuid(); name = "Draft" } }
let mapper = c.CreateMapper()
let sc = mapper.Map<scontainer>(con)
But member mapping isn't called and sc.status contains a string representation of status object(id and name together).
When I add new map:
config.CreateMap<status, string>().ConvertUsing(fun s -> s.name) |> ignore
then sc.status contains correct value.
Does anyone know how to make it work without additional mappings?
Next lines solves my problem:
let c =
AutoMapper.MapperConfiguration(
fun config ->
config.ShouldMapProperty <- fun _ -> false
config.ShouldMapField <- fun _ -> true
)
Metadata produced for constructor is (id, name, status) in both scontainer and container.
Metadata produced for properties is: id, name, status in both scontainer and container.
Metadata produced for fields is: id#, name#, status# in both scontainer and container.
If I don't disable properties usage then automapper will find a match between constructor parameters and properties and will use properties as resolver, which means constructor resolver will be used.
If I disable properties usage, then there will be no match between constructor parameters and fields and constructor will no be used.
I might be wrong but bug is in the next few lines in method: private void MapDestinationCtorToSource(TypeMap typeMap, List ctorParamConfigurations)
in next code:
var resolvers = new LinkedList();
var canResolve = typeMap.Profile.MapDestinationPropertyToSource(typeMap.SourceTypeDetails, destCtor.DeclaringType, parameter.GetType(), parameter.Name, resolvers, IsReverseMap);
if ((!canResolve && parameter.IsOptional) || IsConfigured(parameter))
{
canResolve = true;
}
Here is a test that reproduces a bug
using AutoMapper;
using System;
using Xunit;
namespace ConstructorBug
{
public class Status
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Container
{
public Guid Id { get; set; }
public string Name { get; set; }
public Status Status { get; set; }
}
public class SContainer
{
public SContainer()
{
}
public SContainer(string id, string name, string status)
{
Id = id;
Name = name;
Status = status;
}
public string Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
public class ConstructorBug
{
[Fact]
public void ConstructorMapBug()
{
var mapperConfiguration = new MapperConfiguration(
config =>
{
config.CreateMap<Container, SContainer>()
.ForMember(dest => dest.Status, opts => opts.MapFrom(x => x.Status.Name));
}
);
var mapper = mapperConfiguration.CreateMapper();
var con = new Container
{
Id = Guid.NewGuid(),
Name = "Container 1",
Status = new Status { Id = Guid.NewGuid(), Name = "Draft" }
};
var scon = mapper.Map<SContainer>(con);
Assert.Equal(scon.Id, con.Id.ToString());
Assert.Equal(scon.Name, con.Name);
Assert.Equal(scon.Status, con.Status.Name);
}
}
}

How to search List of name which are present in cosmos documents

I have a list of name. I need to find which name is present in FirstName or LastName Property of Document in Collection.
I had tried the Linq query to archive this but it through error ("Object reference not set to an instance of an object.").
public class UserDoc
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DocumentType { get { return "userdoc"; } private set { } }
}
List<string> Names = new List<string>() { "satya", "singh" };
IEnumerable<UserDoc> Users = await _dBRepository.GetItemsAsync<UserDoc>
(x => (Names.Contains(x.FirstName + " " + x.LastName))&& x.DocumentType == "userdoc");
public async Task<IEnumerable<T>> GetItemsAsync<T>(Expression<Func<T, bool>> predicate) where T : class
{
IDocumentQuery<T> query = _client.CreateDocumentQuery<T>(documentCollectionUri:
UriFactory.CreateDocumentCollectionUri(databaseId: _databaseId, collectionId: _collectionId),
feedOptions: new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
.Where(predicate)
.AsDocumentQuery();
List<T> results = new List<T>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}
According to your description. You code should be modified as below:
IEnumerable<UserDoc> Users = await _dBRepository.GetItemsAsync<UserDoc>
(x => (Names.Contains(x.FirstName)|| Names.Contains(x.LastName))&& x.DocumentType == "userdoc");
I have tested the code and it worked.
According to your error message, i think the the most likely reason is that the object _client point to Null, please check it and try again.

C#: how to display the employee names with lowest salary

I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information.
i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.
here is the class employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
My question is:
How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?
You need to make your class Employee to implement the IComparable interface, then compare the objects against the salary and in the other class sort the array...
Example:
public class Employee :IComparable<Employee>
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public int CompareTo(Employee other)
{
return salary.CompareTo(other.salary);
}
}
private void Find()
{
Array.Sort(employee); // after this Employee is sorted
employee[0];
or
employee[9];
}
this will give a list of lowest salary emplyees
employee.Add(new Employee(17434, "Stephen", "Rad", 9000.00));
employee.Add(new Employee(17435, "Jesse", "Harris", 800.00));
employee.Add(new Employee(17436, "jonatan", "Morris", 9500.00));
var c = employee.OrderBy(i => i.salary).ToList();
var e = employee.Where(i => Math.Abs(i.salary - c[0].salary) < 1).ToList();
Modified you code a little bit
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
//public Employee()
//{
// employeeID = 0;
// fullName = "";
// lastName = "";
// salary = 0.0;
//}
//public Employee(int empIDValue, string fullNameVal, string lastNameVal)
//{
// employeeID = empIDValue;
// fullName = fullNameVal;
// lastName = lastNameVal;
// salary = 0.0;
//}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
and to get min values in list
var minEmpSalarylist = employee.Where(x => x.Salary == employee.Min(y => y.Salary)).ToList();
If default constructor is present then all minEmpSalarylist become initialized with default constructor.
and
employee[0] = new Employee();
to change it to
employee[0] = new Employee(17433, "XXX", "YYY", 8000.00);

ServiceStack OrmLite How can I achieve automatic setting of foreign key/related properties?

I have created the following example to test Foreign Keys and up to this point, it works well. What I would like to be able to do, is use this framework that I built to set the property of the relationship and have it Save the child object when the Parent is saved and automatically set the PrimaryKey and Foreign Key.
The DataManager class exposes the Connection
public class DataManager
{
DataManager()
{
OrmLiteConfig.DialectProvider = SqliteDialect.Provider;
ConnectionString = SqliteFileDb;
updateTables();
}
private void updateTables()
{
using (var dbConn = OpenDbConnection())
{
dbConn.DropAndCreateTable<Person>();
dbConn.DropAndCreateTable<PhoneNumber>();
}
}
public static string SqliteFileDb = "~/App_Data/db.sqlite".MapAbsolutePath();
private static DataManager manager;
public static DataManager Manager {
get
{
if (manager == null)
manager = new DataManager();
return manager;
}
}
public IDbConnection InMemoryDbConnection { get; set; }
public IDbConnection OpenDbConnection(string connString = null)
{
connString = ConnectionString;
return connString.OpenDbConnection();
}
protected virtual string ConnectionString { get; set; }
protected virtual string GetFileConnectionString()
{
var connectionString = SqliteFileDb;
return connectionString;
}
}
These are my POCO's with the BaseClass used to Achieve my results:
public class Person : LiteBase
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
private List<PhoneNumber> numbers;
public List<PhoneNumber> PhoneNumbers {
get
{
if (numbers == null)
numbers = GetList<PhoneNumber>(p => p.Person == Id);
return numbers;
}
}
}
public class PhoneNumber
{
public string Number { get; set; }
public string Description { get; set; }
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
[References(typeof (Person))]
public int Person { get; set; }
public void AddPerson(Person person)
{
Person = person.Id;
}
}
public class LiteBase:INotifyPropertyChanged
{
public List<T> GetList<T>(Expression< Func<T,bool>> thefunction) where T : new()
{
var objects = new List<T>();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
objects = conn.Where<T>(thefunction);
}
return objects;
}
public T GetItem<T>(Expression<Func<T, bool>> thefunction) where T : new()
{
T obj = new T();
using (var conn = Data.DataManager.Manager.OpenDbConnection())
{
obj = conn.Where<T>(thefunction).FirstOrDefault<T>();
}
return obj;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Simple Class to Create Person and PhoneNumber objects
public class PersonManager
{
public void CreatePerson(string name, string surname, string number)
{
using (var conn = DataManager.Manager.OpenDbConnection())
{
var pnum = new PhoneNumber { Number = number };
var person = new Person
{
Name=name,
Surname = surname,
};
conn.Save<Person>(person);
var id = conn.GetLastInsertId();
person.Id = (int)id;
pnum.AddPerson(person);
conn.Save<PhoneNumber>(pnum);
}
}
public List<Person> GetPeople()
{
List<Person> people;
using (var conn = DataManager.Manager.OpenDbConnection())
{
people = conn.Select<Person>();
}
return people;
}
public List<PhoneNumber> GetNumbers()
{
List<PhoneNumber> numbers;
using (var conn = DataManager.Manager.OpenDbConnection())
{
numbers = conn.Select<PhoneNumber>();
}
return numbers;
}
}
And here is the usage:
var manager = new PersonManager();
manager.CreatePerson("John", "Doe", "12345679");
manager.CreatePerson("Jack", "Smith", "12345679");
manager.CreatePerson("Peter", "Jones", "12345679");
manager.CreatePerson("Dan", "Hardy", "12345679");
var people = manager.GetPeople();
var numbers = manager.GetNumbers();
for (int i = 0; i < people.Count; i++)
{
Console.WriteLine("{0} {1} {2}",
people[i].Name,people[i].Surname,people[i].Id);
}
for (int n = 0; n < numbers.Count; n++)
{
Console.WriteLine("PN: {0} {1}",
numbers[n].Number,numbers[n].Person);
}
for (int p = 0; p < people.Count; p++)
{
var person = people[p];
Console.WriteLine("{0}: {1} {2} {3}",
person.Id,person.Name,person.Surname,person.GetItem<PhoneNumber>(x=>x.Person==person.Id).Number);
}
The output is as I expected :
John Doe 1
Jack Smith 2
Peter Jones 3
Dan Hardy 4
PN: 12345679 1
PN: 12345679 2
PN: 12345679 3
PN: 12345679 4
1: John Doe 12345679
2: Jack Smith 12345679
3: Peter Jones 12345679
4: Dan Hardy 12345679
What I really would like to be able to do is the following:
var john = new Person
{
Name = "John",
Surname = "Smith",
PhoneNumber = new PhoneNumber { Number = "123456789" }
};
conn.Save<Person>(john);
var number = john.PhoneNumber.Number
Is this at all possible?
By default OrmLite v3 blobs all complex types properties in a string field and you need to explicitly set all references.
In the next major v4 release (ETA late Nov 2013), OrmLite adds some support for external references with the [Reference] attribute, which lets you tell OrmLite these properties should be stored in an external table and not blobbed, e.g:
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public CustomerAddress PrimaryAddress { get; set; }
[Reference]
public List<Order> Orders { get; set; }
}
This will allow you to call db.SaveReferences() to save the reference properties, e.g:
var customer = new Customer
{
Name = "Customer 1",
PrimaryAddress = new CustomerAddress {
AddressLine1 = "1 Humpty Street",
City = "Humpty Doo",
State = "Northern Territory",
Country = "Australia"
},
Orders = new[] {
new Order { LineItem = "Line 1", Qty = 1, Cost = 1.99m },
new Order { LineItem = "Line 2", Qty = 2, Cost = 2.99m },
}.ToList(),
};
Assert.That(customer.Id, Is.EqualTo(0)); //Id is not saved yet
//Inserts customer, populates auto-incrementing customer.Id
//Specify `references:true` to populate the ForeignKey ids and
//save the related rows as well, e.g:
db.Save(customer, references:true);
Assert.That(customer.Id, Is.GreaterThan(0));
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(customer.Id));
Assert.That(customer.Orders.All(x => x.CustomerId == customer.Id));
Saving References manually
For more fine-grained control you can also choose which references you want to save, e.g:
db.Save(customer); //Doesn't save related rows
//1:1 PrimaryAddress Reference not saved yet
Assert.That(customer.PrimaryAddress.CustomerId, Is.EqualTo(0));
//1:1 PrimaryAddress Reference saved and ForeignKey id populated
db.SaveReferences(customer, customer.PrimaryAddress);
//1:Many Orders References saved and ForeignKey ids populated
db.SaveReferences(customer, customer.Orders);
Loading all related rows with the entity
You can then load the master row and all its references with db.LoadSingleById, e.g:
var dbCustomer = db.LoadSingleById<Customer>(customer.Id);
dbCustomer.PrintDump();
Assert.That(dbCustomer.PrimaryAddress, Is.Not.Null);
Assert.That(dbCustomer.Orders.Count, Is.EqualTo(2));

How do insert a record into a from a string using split function in MVC4?

Hi all i have a string like this which i am passing an ajax function to my controller action method
Brand1~1001=>undefined_undefined|
Category1~2001=>1001_Brand1|
Category2~2002=>1001_Brand1|
Product3~3003=>2002_Category2|
Product4~3004=>Product3~3003|
Product5~3005=>2002_Category2|
Product6~3006=>2002_Category2|
and i have an Menus table in db i had added that as an entity model to my project
Menus
[MenuID],[MenuName],[ParentID]
and i have model like this
public class MenuItems
{
public List<MenuItems> GetALL { get; set; }
public int MenuId { get; set; }
public string MenuName { get; set; }
public int parentId { get; set; }
}
now i want to split the string i have and insert into the above table like this
[MenuID],[MenuName],[ParentID]
1001 ,Brand1 ,null
2001 ,category1 ,1001
2002 ,category2 ,1001
3003 ,product3 ,2002
3004 ,product4 ,3003
3005 ,product5 ,2002
3006 ,product6 ,2002
in the above string Brand1~1001=>undefined_undefined| here Brand1~1001 is the parentmenu and 1001 is the id of the menu
Category1~2001=>1001_Brand1| and here Category1~2001 is the sub menu of the 1001_Brand1 i think you all got waht i amtrying to do can any one help me here please
what i amtrying
public ActionResult MenuDrag()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
string[] list = m.Split('>');
//stuck from here confused what to do next and how do i insert the data in my accordingly
}
}
return View();
}
You are almost there just replace your post method with this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MenuDrag(string menustring)
{
MenuItems items = new MenuItems();
//check the string for empty
if (!String.IsNullOrEmpty(menustring))
{
string[] menus = menustring.Split('|');
foreach (var m in menus)
{
if (m != "")
{
string[] list = m.Split('>');
string[] menu = list[0].Split('~');
string[] parents = list[1].Split('~');
items.MenuItemID = Convert.ToInt16(menu[1]);
items.MenuName = menu[0].ToString();
if (parents[0] == "undefined")
{
items.ParentID = 0;
db.MenuItems.Add(items);
db.SaveChanges();
}
else
{
int parentid=Convert.ToInt16(parents[0]);
var menuid = from me in db.MenusMains where me.MenuItemID == parentid select new { MenuID = me.MenuID };
foreach (var id in menuid)
{
items.ParentID = Convert.ToInt16(id.MenuID);
}
db.MenuItems.Add(items);
db.SaveChanges();
}
}
}
}
return View();
}
}
i had used
if (m != "")
{
}
since u may get an index out of bound exception there since when in your string at this
string[] menus = menustring.Split('|');
u will get an empty ('|') you have to handle this
hope this works

Resources