Scaffold/Generate an object's properties in an initializer - visual-studio-2010

Does anyone know how to "scaffold" or "generate" a constructor block for all of an objects properties? I've got VS2010 with Resharper and am looking to generate something like:
public Customer CustomerB = new Customer
{
firstName = "",
middleName = "",
lastName = "",
additionalPhone = "0",
address1 = "",
address2 = "",
birthDate = new DateTime(),
cellPhone = "",
city = "",
driverLicenseNumber = "",
driverLicenseState = "",
emailAddress = "",
country = "",
fax = "",
grossIncome = 0,
education = null,
leadRequest = null
};
Where I can then double back and fill in the blanks so to speak. Everything i've found is all DatabaseFirst and Getter/Setters Class Properties...

I think it is not possible to generate object initializer for all properties with VS and ReSharper. You need to press Ctrl+Space for every property selection.

Related

How can I retrieve Id of inserted entity using Entity framework Core?

I have a concern since as I am new to using EntityFramework Core, that if I add an object, that I still do not have the id generated by the database, sending the object to it in the transaction, I would add it automatically, this is my code ,
public async Task<ServiceResult<Common.Entities.Company>> SaveCompany(Domain.Models.Company companyModel, Domain.Models.Administrator administratoModel)
{
ServiceResult<Common.Entities.Company> serviceResult = new ServiceResult<Common.Entities.Company>();
try
{
if (user == null && companyExistsRnc == false)
{
Common.Entities.Company myCompany = new Common.Entities.Company
{
CompanyId = companyModel.CompanyId, // The id has not been generated yet,
CompanyName = companyModel.CompanyName,
Rnc = companyModel.Rnc,
CountryId = companyModel.Country.CountryId,
Telephone = companyModel.Telephone,
PersonContact = companyModel.PersonContact,
Address = companyModel.Address,
PhotoPath = companyModel.PhotoPath,
IsActive = false,
};
await _companyRepository.SaveCompany(myCompany); // this is the method that I add the company object to the database and do the savechanges
Common.Entities.User myUser = new Common.Entities.User
{
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
PhoneNumber = administratoModel.Telephone,
Email = administratoModel.Email,
UserName = administratoModel.Email,
IsActive = administratoModel.IsActive,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // here I send the my company object for when I do the savechanges, I think it will add it to me
};
await _userHelper.AddUserAsync(myUser, administratoModel.Password);
await _userHelper.AddUserToRoleAsync(myUser, Common.Core.UserType.Administrator.ToString());
Common.Entities.Administrator myAdministrator = new Common.Entities.Administrator
{
AdministratorId = administratoModel.AdministratorId,
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
Email = administratoModel.Email,
Telephone = administratoModel.Telephone,
IsActive = true,
PhotoPath = administratoModel.PhotoPath,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // company object without the id
User = myUser, // user object without the id
};
await _administratorRepository.SaveAdministrator(myAdministrator);
serviceResult.Data = myCompany;
serviceResult.Message = "CompaƱia agregada!";
}
}
I am new to using entity framework core, and if in case I am wrong in what I am doing please indicate in which part I am doing it wrong, to correct, I await your comments and would appreciate the help,

Kotlin iterator to check if payload list have an id/projectId or not, returning false when there is no attributes?

I have an issue where i have a method where i am checking the payload has the attributes or not. When i am sending my payload i want to check that the user dont have inserted attributes which not allowed in the payload.
My entity class:
#Entity
data class ProjectAssociated(
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(columnDefinition = "BINARY(16)")
var id: UUID? = null,
#Column(columnDefinition = "BINARY(16)")
var projectId: UUID? = null,
#Column(columnDefinition = "BINARY(16)")
var associatedProjectId: UUID? = null
)
My Service class:
fun addAssociatedProjectByProjectId(
projectId: UUID,
projectAssociatedList: MutableList<ProjectAssociated>
): MutableList<ProjectAssociated> {
if (projectAssociatedList.isNotEmpty()) {
println(projectAssociatedList)
if (!projectAssociatedList.map { it.id }.isNullOrEmpty()) {
val errorMessage = "Not allowed to provide parameter 'id' in this request"
throw UserInputValidationException(errorMessage)
}
if (!projectAssociatedList.map { it.projectId }.isNullOrEmpty()) {
val errorMessage = "Not allowed to provide parameter 'projectId' in this request"
throw UserInputValidationException(errorMessage)
}
val checkIds = projectAssociatedList.map {
projectRepository.existsById(it.associatedProjectId)
}
if (checkIds.contains(false)) {
val errorMessage = "One or more ID 'associatedProjectId' not exists"
throw UserInputValidationException(errorMessage)
}
}
return projectAssociatedList.map {
projectAssociatedRepository.save(
ProjectAssociated(
null,
projectId,
it.associatedProjectId
)
)
}.toMutableList()
}
My Controller class:
#ApiOperation("Add associated Projects to a specific Project")
#PostMapping(path = ["/project-associated"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun createAssociatedProjectList(
#ApiParam("The id of the Project", required = true)
#RequestParam("id")
id: UUID,
#ApiParam("JSON object representing the ProjectAssociated")
#RequestBody projectAssociated: MutableList<ProjectAssociated>
): ResponseEntity<WrappedResponse<MutableList<ProjectAssociated>>> {
val createdProjectAssociatedList = projectService.addAssociatedProjectByProjectId(id, projectAssociated)
return ResponseEntity
.status(201)
.location(URI.create("$id/project-associated"))
.body(
ResponseDto(
code = 201,
data = PageDto(list = mutableListOf(createdProjectAssociatedList))
).validated()
)
}
But when i try to send this payload with the project id in #RequestParam:
[
{
"associatedProjectId": "7fe40f90-5178-11ea-9136-1b65a920a5d9"
},
{
"associatedProjectId": "7fe8aaaa-5178-11ea-9136-1b65a920a5d9"
}
]
I have a custom exception where i tell the user if projectId or the id is in the payload that is now allowed to have it in the payload. When i try to POST the payload example above it tells me that projectId or id is in the request? How can that be?
I also printed out the list before if checks:
[ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe40f90-5178-11ea-9136-1b65a920a5d9), ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe8aaaa-5178-11ea-9136-1b65a920a5d9)]
What am I doing wrong?
Thanks for the help!
In the block projectAssociatedList.map { it.id } you are mapping your list to something like [null, null] and it is not null or empty.
So, the complete condition !projectAssociatedList.map { it.id }.isNullOrEmpty() returns true.
If you want to continue using the same logic, you should use !projectAssociatedList.mapNotNull { it.id }.isNullOrEmpty() instead.
The mapNotNull function will filter the null values and output a list just with the not null values. If there is only null values, the list will be empty.
But, a simpler and expressive way to check if there is any not null attribute in a list of objects could be projectAssociatedList.any { it.id != null }

Missing customer name/address information in SquareUp Console using Square.Connect.Api

We are creating a Square 2.0 transaction but when we login to our Square account, the customer name/address information is missing. We are creating a customer address object and populating the properties but they are not showing up in the Square console.
Here is our code:
using Square.Connect.Api;
using Square.Connect.Model;
using Square.Connect.Client;
private static bool RunCreditCardSquare(int? adminId, Models.ReservationReceivePaymentViewModel payment, Models.GuestViewModel guest, String ipaddress, String orderdescription, int reservationId, decimal amountDue)
{
Data.BigRigEntities db = new Data.BigRigEntities();
TransactionsApi transactionsApi = new TransactionsApi();
Square.Connect.Client.Configuration.Default.AccessToken = accessToken;
string uuid = Guid.NewGuid().ToString();
Money amount = new Money((long)amountDue * 100, Money.CurrencyEnum.USD);
// (https://docs.connect.squareup.com/payments/transactions/overview#mpt-overview).
ChargeRequest body = new ChargeRequest(AmountMoney: amount, IdempotencyKey: uuid, CardNonce: payment.CardNonce);
Square.Connect.Model.Address.CountryEnum GuestCountry = Square.Connect.Model.Address.CountryEnum.US;
body.ShippingAddress = new Square.Connect.Model.Address(guest.Address1, "", "", guest.City, "", "", "", "", "", "", guest.PostalCode, GuestCountry, guest.FirstName, guest.LastName, "");
body.BillingAddress = new Square.Connect.Model.Address(guest.Address1, "", "", guest.City, "", "", "", "", "", "", guest.PostalCode, GuestCountry, guest.FirstName, guest.LastName, "");
body.ReferenceId = reservationId.ToString() ;
body.CardNonce = payment.CardNonce;
body.BuyerEmailAddress = guest.EmailAddress;
body.Note = "Conf #:" + reservationId.ToString() + " - " + orderdescription;
var charged = false;
var transactionid = "";
var error = "";
decimal chargeamount = 0.0M;
try
{
var response = transactionsApi.Charge(LocationId, body);
transactionid = response.Transaction.Id;
chargeamount = (decimal) (response.Transaction.Tenders[0].AmountMoney.Amount/100) ;
charged = true;
}
catch (ApiException e)
{
error = e.Message;
}
The shipping address and billing address are only available via API, not the Square Dashboard. To see this information attached to a customer in the Dashboard you should Create a Customer first and then pass the customer_id along when you charge.

LINQ query for WHERE IN clasue

I've 4 tables Transactions, Attachment, SubReportType & SubRepRole. I'm having user roles on my Cache. I want to have those attachments which are related with User roles[a user may have multiple role]
List<int> userrole = new List<int>();
UserContext user_details = (UserContext)HttpContext.Current.Cache["UserContext"];
IList<UserRole> userrole_id = user_details.UserRoleModuleWise;
var query = (from trans in objContext.Transactions
join attch in objContext.Attachment on trans.TransId equals attch.TransId
join subrept in objContext.SubReportType on trans.SubRepId equals subrept.SubRepId
join subreprl in objContext.SubRepRole on trans.SubRepId equals subreprl.SubRepId
join selectedrole in userrole_id on subreprl.RoleId equals selectedrole.RoleId
/*where obj.Contains(subreprl.RoleId) */orderby trans.TransDate
select new AttachmentModel
{
Createdate = attch.CreatedDateTime,
FileType = attch.FileType,
FileName = attch.FileName,
Attachid = attch.AttachedId,
FileTag = attch.FileTag,
Transid = trans.TransId,
SubReportName = subrept.SubRepName,
RandomPinNo = attch.FileRandomPin
}).ToList();
Now getting this error:
Unable to create a constant value of type
'User.Common.DataContract.UserRole'. Only primitive types or
enumeration types are supported in this context.
Please help on this. Tried "Contains" too but type casting error is coming. Just wanted to have those records where roles are in user_details.UserRoleModuleWise. user_details.UserRoleModuleWise is an array with RoleId and RoleName
You need to use Contains with an array of the correct values:
where user_details.UserRoleModuleWise.Select(urmw => urmw.RoleId).ToArray().Contains(aRoleId => aRoleId == subreprl.RoleId)
Created a common class --
object[] common_data = new object[4];
UserContext user_details = (UserContext)HttpContext.Current.Cache["UserContext"];
List<UserRole> userrole_id = user_details.UserRoleModuleWise.ToList();
int[] roleid = { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20 };
string[] rolename = { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };
for (int i = 0; i < userrole_id.Count; i++)
{
roleid[i] = Convert.ToInt32(userrole_id[i].RoleId);
rolename[i] = Convert.ToString(userrole_id[i].RoleName);
r_id.Add(roleid[i], rolename[i]);
}
common_data[0] = roleid;
common_data[1] = rolename;
//common_data[2] = username;
common_data[3] = userrole_id.Count;
then in my repository i used -
User_common_data ucd = new User_common_data();
object[] ucd_data = ucd.user_common_details();
int[] roles = (int[]) ucd_data[0];
var query = (from obj in objContext.ReportType
join obj1 in objContext.SubReportType on obj.RepId equals obj1.RepId
join obj2 in objContext.SubRepRole on obj1.SubRepId equals obj2.SubRepId
where roles.Contains(obj2.RoleId)
select new ReportTypeModel
{
RepId = obj.RepId,
RepName = obj.RepName,
RepCode = obj.RepCode
}).ToList();
now its working fine. #NetMage's answer also worked... thanks

asp.net mvc3, why my dropdownlist is not selected?

I create my selectlist from enum.
[Flags]
public enum Age
{
New_Born = 1,
Toddler = 2,
Preschool = 4,
Kindergarten = 8,
Elementary_School = 16,
Middle_School = 32,
High_School = 64
}
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = (int)e, Name = e.ToString().Replace("_", " ") };
I tried both:
var ageList = new SelectList(age, "Id", "Name", (int)Model.Child.Age);
or
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);
#Html.DropDownListFor(m => m.Child.Age, ageList, "Your Child's Age")
Everything works except the selected value didn't get selected.
EDIT: after hours testing, finally fix it.
chagne Id = (int)e to Id = e.
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = e, Name = e.ToString().Replace("_", " ") };
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);
I just created a similar example and worked out your problem and I believe you have two problems with your code:
In your controller code, you should have your first option, like this:
SelectList selectList = new SelectList(items, "Id", "Name", (int)Qualities.Whatever);
And in your view:
<%= this.Html.DropDownListFor(m => m.List.SelectedValue, this.Model.List, "Qualities") %>
Think about it, why would you pass the SelectList twice? You should pass the selected value and then the list of values.
The fact that I didn't use Razor view engine is irrelevant.
after hours testing, finally fix it. chagne Id = (int)e to Id = e.
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = e, Name = e.ToString().Replace("_", " ") };
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);

Resources