Asp.net core: count hotel booking date - asp.net-core

Is there any way to count the day of booking? either using lambda or sqlite query thanks, can find the solution for a while thanks~
The bookingInput is from a webpage of booking which contains rooms, checkin and check out.
The below code is Create.cshtml.cs in Booking folder (created by scaffolding)
int count = bookingInput.CheckOut.DayOfWeek - booking.CheckIn.DayOfWeek;
booking.Cost = count * theRoom.Price;

You could use the TimeSpan.TotalDays Property to get the number of days between two dates.
Check the following code:
//get data from the Repository.
var result = _repo.GetBookings().Select(c => new
{
Id = c.Id,
Name = c.Name,
RoomNumner = c.RoomNumber,
CheckIn = c.CheckIn,
CheckOut = c.CheckOut,
Days = (c.CheckOut - c.CheckIn).TotalDays,
RoundDays = Math.Round((c.CheckOut - c.CheckIn).TotalDays)
});
The result as below:
The test data in the Repository:
public interface IDataRepository
{
List<BookingViewModel> GetBookings();
}
public class DataRepository : IDataRepository
{
public List<BookingViewModel> GetBookings()
{
return new List<BookingViewModel>()
{
new BookingViewModel(){ Id=101, Name="David", RoomNumber=1001, CheckIn= new DateTime(2021,1,18,15,30,0), CheckOut=DateTime.Now },
new BookingViewModel(){ Id=102, Name="Jack", RoomNumber=2001, CheckIn= new DateTime(2021,1,15,10,30,0), CheckOut=DateTime.Now },
new BookingViewModel(){ Id=103, Name="Tom", RoomNumber=3001, CheckIn= new DateTime(2021,1,20,18,30,0), CheckOut=DateTime.Now },
};
}
}

Related

Seed method doesn't update database second time after editing it. What to do?

I create web app using ASP.Net Core 2.1 MVC. To add initial data to some tables (for ex. categories) I wrote Seed method and added Migration and updated database successfully (with no errors). Data (with all values added) was seen in the database (SQL Server) after running application. Then I added some other categories in the seed method. This time I didn't see changes (updates) in SQL server after running application and updating database using migration.
Does Seed work only first time or I can somehow update (increase initial data) the database using Seed?
This is my Seed method:
public static void Seed(OfferDbContext offerDbContext)
{
if (!offerDbContext.Categories.Any())
{
Category avto = new Category()
{
Name = "Avto"
};
Category home = new Category()
{
Name = "Ev"
};
Category digital = new Category()
{
Name = "Digital"
};
Category household = new Category()
{
Name = "Məişət"
};
Category entertainment = new Category()
{
Name = "Əyləncə"
};
Category furniture = new Category()
{
Name = "Mebel"
};
Category clothes = new Category()
{
Name = "Geyim"
};
Category cafe = new Category()
{
Name = "Kafe"
};
Category food = new Category()
{
Name = "Qida"
};
Category edu = new Category()
{
Name = "Təhsil"
};
Category medical = new Category()
{
Name = "Tibb"
};
Category tourism = new Category()
{
Name = "turizm"
};
offerDbContext.Categories.AddRange(avto, home, digital, household, entertainment, furniture, clothes, cafe, food, edu, medical, tourism);
offerDbContext.SaveChanges();
}
}
And Main method in Program.cs where I call that Seed:
public static void Main(string[] args)
{
IWebHost webHost = CreateWebHostBuilder(args).Build();
using (IServiceScope serviceScope = webHost.Services.CreateScope())
{
using(OfferDbContext offerDbContext = serviceScope.ServiceProvider.GetRequiredService<OfferDbContext>())
{
OfferDb.Seed(offerDbContext);
}
}
webHost.Run();
}
I would think that the issue is with the below line
if (!offerDbContext.Categories.Any())
Basically it says if there are no categories then do the adds, there is no else so if there are already categories there it will do nothing.
So maybe throw an else in and if there are already categories just add the new ones,
OR
Potentially you could wrap each of the creates in an if to see if it already exists and if it does not then crate it.

I want to select different packages on the basis of states, how to get value

public ActionResult Rajasthan()
{
//List<PackageGallery> all = new List<PackageGallery>();
using (travelAndTourismEntities objentity = new travelAndTourismEntities())
{
List<PackageGallery> all = (from p in objentity.PackageGalleries where p.ParentCategory == "Rajasthan" orderby p.Imageid select p).ToList();
// all = objentity.PackageGalleries.ToList();
return View(all);
}
}
I am writing this query but this is specific to rajasthan only how to make it generalize
You can create a parameter to your action method where you accept the state name you want to use in your filter.
public ActionResult PackageGalleries(string id)
{
var all = new List<PackageGallery>();
using (var db = new travelAndTourismEntities())
{
all = db.PackageGalleries
.Where(s=>s.ParentCategory==id)
.OrderBy(x=>x.ImageId).ToList();
}
return View(all);
}
And you can call it like yourSiteName/yourControllerName/PackageGalleries/rajasthan or yourSiteName/yourControllerName/PackageGalleries/kerala
The last part of the url will be mapped to the id parameter of the action method.

Ravendb LoadDocument showing NULL value

I have following two Collections in RavenDB.Please help me for creating index for getting data from both collection.
public class Ticket
{
public string TicketID{get;set;}
public double Total{get;set;}
}
public class ImportTiming
{
public string Id{get;set;}
public DateTime ExtractTime{get;set;}
}
AND
public class ResultClass
{
public string TicketID{get;set;}
public double Total{get;set;}
public DateTime ExtractTime{get;set;}
}
TicketID(Ticket) & Id(ImportTiming) are same.I am using LoadDocument for ExtractTime but it is showing NULL value.
Thanks in advance!!!
Finally i got solution...
Bellow is the Map-Reduce function,in which i have used LoadDocument<> for selecting data from ImportTiming Document.
public class IdxJoinBetweenCollections : AbstractIndexCreationTask<Ticket,JoinBetweenCollections.ResultClass>
{
public IdxJoinBetweenCollections()
{
Map = docs => from doc in docs
let TimeDoc = LoadDocument<ImportTiming>("ImportTiming/" + doc.TicketID)
select new
{
ID = doc.TicketID,
Total = doc.Total,
ExtractTime = TimeDoc.ExtractComplete,
};
Reduce = results => from res in results
group res by res.ID into g
select new
{
ID = g.Key,
Total = g.Select(x => x.Total).FirstOrDefault(),
ExtractTime = g.Select(x => x.ExtractTime).FirstOrDefault(),
};
}
}
In LoadDocument("ImportTiming/" + doc.TicketID),i have used CollectionName followed by Id so that i gets whole document.If i dont use CollectionName then it shows NULL value.
Reference:http://ravendb.net/docs/2.0/client-api/querying/static-indexes/indexing-related-documents

MS Dynamics CRM. Get users who current record shared with

I have a entity record which is shared with or more users. I would like to unshare this record when Deactivate it. I want to do that in Plugin. But I can't understand how to get all users from sharing list who have access to this record. How to do that?
Here is my code snippet:
protected void ExecutePostPersonSetStateDynamicEntity(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
var context = localContext.PluginExecutionContext;
var targetEntity = (Entity)context.InputParameters["EntityMoniker"];
var state = (OptionSetValue)context.InputParameters["State"];
var columns = new ColumnSet(new[] { "statecode" });
var retrivedEntity = localContext.OrganizationService.Retrieve(targetEntity.LogicalName, targetEntity.Id, columns);
if (state.Value == 1)
{
RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
{
Target = new EntityReference(personEntity.LogicalName, personEntity.Id),
Revokee = new EntityReference(neededEntity.LogicalName, needed.Id)
};
// Execute the request.
}
}
As you can see, I need an entity "neededEntity", I don't know how to get it from "targetEntity" or "retrievedEntity".
You need to use a RetrieveSharedPrincipalsAndAccessRequest
http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.retrievesharedprincipalsandaccessrequest.aspx
You can start from the included example, basically inside the foreach you call your RevokeAcessRequest

RavenDB sum of a count

I'm trying to do a sum of a count of a child collection in a Raven query. It is returning a count of 0. If I use the same LINQ on the object directly, then it works with a count of 2.
Is this query possible with auto-indexing on Raven? If I need to create a map-reduce index, can someone help me with that?
[TestMethod]
public void CalculateUserClickCount()
{
var db = new EmbeddableDocumentStore { RunInMemory = true };
db.Initialize();
using (var session = db.OpenSession())
{
var user = new User();
var product = new Product();
product.Clicks.Add(new Click());
product.Clicks.Add(new Click());
user.Storefront.EndoProducts.Add(product);
session.Store(user);
session.SaveChanges();
var users = session.Query<User>()
.Customize(t => t.WaitForNonStaleResults())
.Select(t => new
{
StoreFrontId = t.Storefront.StorefrontID,
itemCount = t.Storefront.EndoProducts.Count,
updateDate = t.Storefront.LastUpdateDate,
clickCount = t.Storefront.EndoProducts.Sum(r => r.Clicks.Count), // this is improperly set to 0
TotalAffiliateRevenue = t.Storefront.SaleReports.Sum(r => r.TotalAffiliateEarnings) // this works
})
.ToList();
int clickCount = user.Storefront.EndoProducts.Sum(t => t.Clicks.Count); // this is properly set to 2
Assert.AreEqual(2, users[0].clickCount);
}
}
You don't need a map/reduce for this, because you are only operating on a single document at any time.
What you do need it s transform results, most probably, to do this.