I want to get client machine date format, my application is hosted on US machine.
Hosting Server date format : MM/dd/yyyy
Local(Client) machine date format: dd/MM/yyyy
I want to get dd/MM/yyyy format which is the format of the client machine.
I have used the following code but it returns server date format(MM/dd/yyyy) but I want client machine date format(Local).
DateTimeFormatInfo info = new DateTimeFormatInfo
{
ShortDatePattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
};
Can anyone please tell how to get client machine date format(dd/MM/yyyy)?
In MVC asp.net :
Frist put Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Request.UserLanguages.FirstOrDefault());into Application_BeginRequest
if you don't have Application_BeginRequest. Please click Global.asaxin your project.
add new function in MvcApplication class
protected void Application_BeginRequest() {
Thread.CurrentThread.CurrentCulture = new
System.Globalization.CultureInfo(Request.UserLanguages.FirstOrDefault());
}
now , you could use format of DateTime.Now with client machine
For Retrieving Client date format. I think java-script would be the best option
Try below code. I hope it will help.
getDateFormat(){
// initialize date value "31st January 2019"
var my_date = new Date(2019,0,31);
console.log(my_date.toLocaleDateString());
// Initialize variables
var separator="";
var first="";
var second="";
var third="";
var date_parts = [];
// get separator : "-", "/" or " ", format based on toLocaleDateString function
if (my_date.toLocaleDateString().split("-").length==3){
separator = " - ";
date_parts = my_date.toLocaleDateString().split("-");
}
if (my_date.toLocaleDateString().split("/").length == 3) {
separator = " / ";
date_parts = my_date.toLocaleDateString().split("/");
}
if (my_date.toLocaleDateString().split(" ").length == 3) {
separator = " ";
date_parts = my_date.toLocaleDateString().split(" ");
}
// get first part
if (date_parts[0]==2019){
first ="yyyy";
} else if (date_parts[0] == 31){
first = "dd";
} else{
if (date_parts[0].length<=2){
first ="mm";
}
else{
first="mmm";
}
}
// get second part
if (date_parts[1] == 2019) {
second = "yyyy";
} else if (date_parts[1] == 31) {
second = "dd";
} else {
if (date_parts[1].length <= 2) {
second = "mm";
}
else {
second = "mmm";
}
}
// get third part
if (date_parts[2] == 2019) {
third = "yyyy";
} else if (date_parts[2] == 31) {
third = "dd";
} else {
if (date_parts[2].length <= 2) {
third = "mm";
}
else {
third = "mmm";
}
}
// assembly
var format = first + separator + second + separator + third;
console.log(format);
return format;
}
Related
I'm trying to access Amazon MWS API from my .Net application, using Products API Section Client Library - C# (https://developer.amazonservices.com/doc/products/products/v20111001/cSharp.html/138-8219342-3408216)
Everything works fine, except for GetMyFeesEstimate calls.
I use this method from example:
public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate()
{
// Create a request.
GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
string sellerId = "example";
request.SellerId = sellerId;
string mwsAuthToken = "example";
request.MWSAuthToken = mwsAuthToken;
FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
request.FeesEstimateRequestList = feesEstimateRequestList;
return this.client.GetMyFeesEstimate(request);
}
And I add item to FeesEstimateRequestList like this:
feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
{
MarketplaceId = marketplaceId,
IdType = "ASIN",
IdValue = "B0078LENZC",
PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 30.49M, CurrencyCode = "GBP" }, Shipping = new MoneyType { Amount = 3.5M, CurrencyCode = "GBP" }, Points = new Points { PointsNumber = 0 } },
Identifier = "request_" + Guid.NewGuid().ToString(),
IsAmazonFulfilled = false
});
But constantly get MalformedInput error with no message describing what is wrong:
<ErrorResponse
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<Error>
<Type>Sender</Type>
<Code>MalformedInput</Code>
</Error>
<RequestId>f79b9147-90d7-4ea2-b51c-d6c37c6a1bd0</RequestId>
</ErrorResponse>
Have someone any ideas how to make it work?
I have found solution:
Due to my OS regional settings, decimal separator in price had being set to comma, instead of dot when converting parameters to string.
I have to modify method putValue of MwsAQCall class like this:
private void putValue(object value)
{
if (value==null)
{
return;
}
if (value is IMwsObject)
{
parameterPrefix.Append('.');
(value as IMwsObject).WriteFragmentTo(this);
return;
}
string name = parameterPrefix.ToString();
if (value is DateTime)
{
parameters.Add(name, MwsUtil.GetFormattedTimestamp((DateTime)value));
return;
}
string valueStr = value.ToString();
if (value is decimal)
{
valueStr = valueStr.Replace(",", ".");
}
if (valueStr==null || valueStr.Length==0)
{
return;
}
if (value is bool)
{
valueStr = valueStr.ToLower();
}
parameters.Add(name, valueStr);
}
I am trying to open Outlook 2013 New Appointment window at Client side with ASP.Net c# application. my code is working fine its a simple button. when i click the button from client machine this application open the outlook window on server/host machine but not on Client Machine.
what can i use to open Outlook Appointment window on client machine by using ASP.Net C#.
I am using following code:
private void OpenOutlookAppt() {
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook.AppointmentItem appt = null;
app = new Microsoft.Office.Interop.Outlook.Application();
appt = (Microsoft.Office.Interop.Outlook.AppointmentItem)app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem);
appt.Subject = "Customer Review";
appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
appt.Location = "36/2021";
appt.Start = Convert.ToDateTime("3/30/2016 01:30:00 PM");
appt.End = Convert.ToDateTime("3/30/2016 02:30:00 PM");
Outlook.Recipient recipRequired =
appt.Recipients.Add("abc#domain.com");
recipRequired.Type =
(int)Outlook.OlMeetingRecipientType.olRequired;
Outlook.Recipient recipOptional =
appt.Recipients.Add("abc#domain.com");
recipOptional.Type =
(int)Outlook.OlMeetingRecipientType.olOptional;
Outlook.Recipient recipConf =
appt.Recipients.Add("Conf Room 36/2021 (14) AV");
recipConf.Type =
(int)Outlook.OlMeetingRecipientType.olResource;
appt.Recipients.ResolveAll();
appt.Display(true); }
Thanks
Your code runs on the server under IIS, so of course you end up using Outlook on the server machine. And Outlook cannot be used in a service (such as IIS).
Your options are:
Client side Java Script. IE only. Your site must be trusted to be able to create COM objects ("Outlook.Applicatuion").
Create an iCal (ICS) file on the server. When the end user opens it, saving it will create an appointment in Outlook.
I think the best way to achieve this is by generating an ICS file on the server for the web user to download and open.
The ICS file format is quite simple:
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
STATUS:TENTATIVE
DTSTART:20160330T013000Z
DTEND:20160330T023000Z
SUMMARY;ENCODING=QUOTED-PRINTABLE:Customer Review
LOCATION;ENCODING=QUOTED-PRINTABLE:Conf Room 36/2021 (14) AV
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:Customer Review Meeting
END:VEVENT
END:VCALENDAR
Code for generating file content:
public class CalendarFile
{
private CfStatus _status = CfStatus.Busy;
private string _location = "";
private string _description = "";
public CalendarFile(string title, DateTime startDate, DateTime endDate)
{
if (startDate > endDate)
throw new Exception("Attept to initialize a calendar event with start date after end date");
Summary = title;
StartDate = startDate;
EndDate = endDate;
}
public enum CfStatus { Free, Busy, Tentative, OutOfTheOffice };
override public string ToString()
{
var calEvent = new StringBuilder();
calEvent.AppendLine("BEGIN:VCALENDAR");
calEvent.AppendLine("VERSION:2.0");
calEvent.AppendLine("BEGIN:VEVENT");
switch (Status)
{
case CfStatus.Busy:
calEvent.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
break;
case CfStatus.Free:
calEvent.AppendLine("TRANSP:TRANSPARENT");
break;
case CfStatus.Tentative:
calEvent.AppendLine("STATUS:TENTATIVE");
break;
case CfStatus.OutOfTheOffice:
calEvent.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:OOF");
break;
default:
throw new Exception("Invalid CFStatus");
}
if (AllDayEvent)
{
calEvent.AppendLine("DTSTART;VALUE=DATE:" + ToCFDateOnlyString(StartDate));
calEvent.AppendLine("DTEND;;VALUE=DATE:" + ToCFDateOnlyString(EndDate));
}
else
{
calEvent.AppendLine("DTSTART:" + ToCFString(StartDate));
calEvent.AppendLine("DTEND:" + ToCFString(EndDate));
}
calEvent.AppendLine("SUMMARY;ENCODING=QUOTED-PRINTABLE:" + ToOneLineString(Summary));
if (Location != "") calEvent.AppendLine("LOCATION;ENCODING=QUOTED-PRINTABLE:" + ToOneLineString(Location));
if (Description != "") calEvent.AppendLine("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + ToCFString(Description));
calEvent.AppendLine("END:VEVENT");
calEvent.AppendLine("END:VCALENDAR");
return calEvent.ToString();
}
public string Summary { get; set; }
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; private set; }
public string Location
{
get { return _location; }
set { _location = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public bool AllDayEvent { get; set; }
public CfStatus Status
{
get { return _status; }
set { _status = value; }
}
private static string ToCFString(DateTime val)
{
//format: YYYYMMDDThhmmssZ where YYYY = year, MM = month, DD = date, T = start of time character, hh = hours, mm = minutes,
//ss = seconds, Z = end of tag character. The entire tag uses Greenwich Mean Time (GMT)
return val.ToUniversalTime().ToString("yyyyMMddThhmmssZ");
}
private static string ToCFDateOnlyString(DateTime val)
{
//format: YYYYMMDD where YYYY = year, MM = month, DD = date, T = start of time character, hh = hours, mm = minutes,
//ss = seconds, Z = end of tag character. The entire tag uses Greenwich Mean Time (GMT)
return val.ToUniversalTime().ToString("yyyyMMdd");
}
private static string ToCFString(string str)
{
return str.Replace("r", "=0D").Replace("n", "=0A");
}
private static string ToOneLineString(string str)
{
return str.Replace("r", " ").Replace("n", " ");
}
}
ASP.NET WebForms page:
public partial class Appointment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var calFile = new CalendarFile("My Event", new DateTime(2016,3, 30, 5),
new DateTime(2016,3, 30, 6));
calFile.Location = "Conf Room 36/2021";
calFile.Description = "Review meeting";
calFile.Status = CalendarFile.CfStatus.Busy;
calFile.allDayEvent = false;
Response.AddHeader("content-disposition", "attachment; filename=PTO%20Request.ics");
Response.ContentType = "text/x-vCalendar";
Response.Write(calFile.ToString());
}
}
I have an web application where I parse a csv file that can have over 200k records in it. I parse each line for information, verify that the key does not exist in the database and then add it to the context. When the count reaches 10,000 records it calls SaveChanges routine. The problem is that there can be duplicates in the context and it errors out. This is running on a Azure VM communicating to an Azure SQL server.
Two questions, how do I handle the duplicate issue and is there any way I can improve the speed as it takes several hours to run?
using (LoanFileEntities db = new LoanFileEntities())
{
db.Configuration.AutoDetectChangesEnabled = false; // 1. this is a huge time saver
db.Configuration.ValidateOnSaveEnabled = false; // 2. this can also save time
while (parser.Read())
{
counter++;
int loan_code = 0;
string loan_code_string = parser["LoanId"];
string dateToParse = parser["PullDate"].Trim();
DateTime date_pulled;
try
{
date_pulled = DateTime.Parse(dateToParse, CultureInfo.InvariantCulture);
}
catch (Exception)
{
throw new Exception("No Pull Date for line " + counter);
}
string originationdate = parser["OriginationDate"].Trim();
DateTime date_originated;
try
{
date_originated = DateTime.Parse(originationdate, CultureInfo.InvariantCulture);
}
catch (Exception)
{
throw new Exception("No Origination Date for line " + counter);
}
dateToParse = parser["DueDate"].Trim();
DateTime date_due;
try
{
date_due = DateTime.Parse(dateToParse, CultureInfo.InvariantCulture);
}
catch (Exception)
{
throw new Exception("No Due Date for line " + counter);
}
string region = parser["Region"].Trim();
string source = parser["Channel"].Trim();
string password = parser["FilePass"].Trim();
decimal principalAmt = Convert.ToDecimal(parser["Principal"].Trim());
decimal totalDue = Convert.ToDecimal(parser["TotalDue"].Trim());
string vitaLoanId = parser["VitaLoanId"];
var toAdd =
db.dfc_LoanRecords.Any(
x => x.loan_code_string == loan_code_string);
if (!toAdd)
{
dfc_LoanRecords loan = new dfc_LoanRecords();
loan.loan_code = loan_code;
loan.loan_code_string = loan_code_string;
loan.loan_principal_amt = principalAmt;
loan.loan_due_date = date_due;
loan.date_pulled = date_pulled;
loan.date_originated = date_originated;
loan.region = region;
loan.source = source;
loan.password = password;
loan.loan_amt_due = totalDue;
loan.vitaLoanId = vitaLoanId;
loan.load_file = fileName;
loan.load_date = DateTime.Now;
switch (loan.region)
{
case "UK":
if (location.Equals("UK"))
{
//db.dfc_LoanRecords.Add(loan);
if (loan.source == "Online")
{
counter_new_uk_online++;
}
else
{
counter_new_uk_retail++;
}
}
break;
case "US":
if (location.Equals("US"))
{
db.dfc_LoanRecords.Add(loan);
if (loan.source == "Online")
{
counter_new_us_online++;
}
else
{
counter_new_us_retail++;
}
}
break;
case "Canada":
if (location.Equals("US"))
{
db.dfc_LoanRecords.Add(loan);
if (loan.source == "Online")
{
counter_new_cn_online++;
}
else
{
counter_new_cn_retail++;
}
}
break;
}
// delay save to speed up load. 3. also saves transactional time
if (counter % 10000 == 0)
{
db.SaveChanges();
}
}
} // end of parser read
db.SaveChanges();
}
}
}
I would suggest removing duplicates in the code before sending it over to .SaveChanges().
Instead of going into detail about duplicate removal, I've put together this list of links to existing questions and answers on StackOverflow that may help:
Delete duplicates using Lambda
Using DISTINCT on a subquery to remove duplicates in Entity Framework
Using LINQ to find / delete duplicates
Hope that helps!
I am using jquery ajax to request a list of objects from a database via a c# web method:
[WebMethod]
public static List<SessionQueue> GetActiveIssues()
{
try
{
return MyContext.SessionQueues.Where(x => !x.Resolved).OrderBy(d => d.SubmittedTime).ToList();
}
catch (Exception ex)
{
throw new Exception(ex.ToString()); // catch in jquery
}
}
Each SessionQueue object has a property:
public System.DateTime SubmittedTime
When I receive the SubmittedTime in jquery, the date looks like this:
/Date(1445975227197)/
How do I parse this to a valid date string? e.e mm/dd/yy xx:xx am
I have tried:
function formatLongDate(date) {
var nd = Date.parse(date);
var dt = new Date(nd);
var dtStr = $.datepicker.formatDate("mm/dd/yy", dt) + ' ' + getTime(date)
return dtStr;
}
but /Date(1445975227197)/ is not a valid date ticks
Try using String.prototype.match() , Array.protottpe.map()
new Date("/Date(1445975227197)/".match(/\d+/).map(Number)[0])
MVC Converts dates to the number of milliseconds from Jan 1, 1970. The simplest way to convert it to a javascript date is to do the following
var convertedDate = new Date(parseInt(SubmittedTime.substr(6)));
Calendar calendar = Calendar.getInstance();
//timestamp is where you're getting the 1445975227197
calendar.setTimeInMillis(timeStamp);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
I have to display a validation message when a user selects a date outside the allowed range. The is the code i have to work with:
public ActionResult QuickEdit(int pk, string name, string value)
{
var freeOfChargeTime = Db.FreeOfChargeTime.Find(pk);
freeOfChargeTime.ProjectExtension = freeOfChargeTime.ProjectExtension ?? Db.ProjectExtensions.Find(freeOfChargeTime.ProjectExtensionId);
if ((name == "StartDate" && DateTime.Parse(value) > freeOfChargeTime.EndDate) || (name == "EndDate" && DateTime.Parse(value) < freeOfChargeTime.StartDate))
{
ModelState.AddModelError("StartDate", "the end date must be after the start date");
}
if (name == "NumberOfDays" && double.Parse(value) <= 0)
{
ModelState.AddModelError("NumberOfDays", "Number of days must be > 0");
}
if (name == "StartDate" && DateTime.Parse(value) < freeOfChargeTime.ProjectExtension.StartDate)
{
ModelState.AddModelError("StartDate", "the free of charge period start date must be after the project extension start date");
}
if (freeOfChargeTime.ProjectExtension is IPextWithEndDate)
{
var poWithEndDate = (IPextWithEndDate)freeOfChargeTime.ProjectExtension;
if (name == "EndDate" && DateTime.Parse(value) > poWithEndDate.EndDate)
{
ModelState.AddModelError("EndDate", "the free of charge period end date must be before the project extension end date");
}
}
if (freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Cancelled ||
freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Disabled)
{
ModelState.AddModelError("Status", "the project extension is cancelled or disabled");
}
if (ModelState.IsValid) return XEditableUpdate(Db.FreeOfChargeTime, pk, name, value);
Response.StatusCode = 400;
var error = new Error { Message = "Error: " + ModelState.Errors() };
return Json(error.Message, JsonRequestBehavior.AllowGet);
}
This displays "Error: the free of charge period start date must be after the project extension start date\n"
I have tried:
#*#1*#
error.Message = error.Message.Split('\\').First();
#*#2*#
error.Message = error.Message.Replace("\\n", " ");
#*#3*#
string validationMessage = error.Message.Split('\\').First();
#*#4*#
string validationMessage = error.Message.Replace("\\n", " ");
#*#5*#
string validationMessage = error.Message;
validationMessage = validationMessage.Split('\\').First();
#*#6*#
string validationMessage = error.Message;
validationMessage = validationMessage.Replace("\\n", " ");
I still get the same result. Is there any way to get rid of the "\n", or work around the problem?
validationMessage.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
Use this code.