How can parse DateTime in web service method - c#

I have build a web service with web api in c#.
I have created a method to retrieve some record from database. One column of it, is datetime. I want format it.
So I have this method to retrieve the records from database:
[NonAction]
private IQueryable<WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO> getSecSocImages(int? id)
{
var strItem = from u in db_data.CAMERA_SEC_SOC
where u.ID == id
select u.Image;
String imageBas64 = GetString(strItem.First());
if (id != null)
{
return from u in db_data.CAMERA_SEC_SOC
where u.ID == id
select new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO()
{
image = imageBas64,
image_width = u.image_width,
image_height= u.image_height,
type = u.type,
timestamp =u.timestamp.ToString(),
dateTime = u.timestamp,
rectangle = new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO.Rectangle()
{
rects = from pi in db_data.CAMERA_SEC_SOC_Rectangles
where pi.ID_SecSoc == id
select new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO.Rectangle.Rect()
{
height= pi.height,
width = pi.width,
x = pi.x,
y=pi.y
}
}
};
}
return null;
}
This is the method to create a response:
public HttpResponseMessage getSecSocData(int? id = null)
{
try
{
IQueryable<ImmaginiSecSoc.ImmaginiSecSocDTO> lista = getSecSocImages(id);
List<ImmaginiSecSoc.ImmaginiSecSocDTO> listaModificata = new List<ImmaginiSecSoc.ImmaginiSecSocDTO>();
foreach (ImmaginiSecSoc.ImmaginiSecSocDTO a in lista)
{
a.timestamp = a.dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff");
listaModificata.Add(a);
}
return Request.CreateResponse(HttpStatusCode.OK, new RCamera((short)status_code.Success, "Ok", listaModificata));
}
catch (Exception e)
{
e = e.GetBaseException();
log.Error(string.Format("{0} {1}", e.Message, e.StackTrace));
return Request.CreateResponse(HttpStatusCode.InternalServerError, new RMessage((short)status_code.Exception, HttpStatusCode.InternalServerError.ToString()));
}
}
As you can see, I must cycle the list and formatting the field timestamp.
Now my question is, how can I change the code o the parse JSON to formatting my date?

You're already doing
timestamp =u.timestamp.ToString(),
in getSecSocImages method,
If the format is always the same, change it to
timestamp =u.timestamp.ToString("MM/dd/yyyy HH:mm:ss.fff"),

Related

Cannot implicitly convert type 'Model.RouteListModel' to 'string'

I am facing this error:
Cannot implicitly convert type 'Model.RouteListModel' to 'string'
ReportModel class:
public class RouteGroup
{
public IGrouping<string, RouteImportModel> Data { get; set; }
}
public class RouteImportModel
{
..
..
}
public class RouteListModel
{
..
..
}
The Service class has the following method which saves data imported from the excel file into various tables of the database:
public RouteListModel GetRouteSaveObj(RouteGroup model, User userInfo)
{
var temp = model.Data.ToList();
var areaTemp = temp.Select(x => x.AREA).Distinct().ToList();
var AreaQuery = $"SELECT AREA_CODE FROM DIST_AREA_MASTER WHERE UPPER(AREA_NAME) IN (UPPER(TRIM('{String.Join("')),UPPER(TRIM('", areaTemp)}')))";
var result = new RouteListModel
{
ROUTE_NAME = temp[0].ROUTE_NAME,
ROUTE_TYPE = temp[0].ROUTE_TYPE,
AREA_CODE = _objectEntity.SqlQuery<string>(AreaQuery).ToList()
};
var entities = new List<RouteEntityModel>();
var sn = 1;
foreach (var item in temp)
{
var query = "";
if (item.ENTITY_TYPE == "D")
query = $"SELECT TO_CHAR(CUSTOMER_CODE) FROM SA_CUSTOMER_SETUP WHERE CUSTOMER_EDESC = '{item.ENTITY}' AND COMPANY_CODE='{userInfo.company_code}' AND DELETED_FLAG='N'";
if (item.ENTITY_TYPE == "R")
query = $"SELECT TO_CHAR(RESELLER_CODE) FROM DIST_RESELLER_MASTER WHERE RESELLER_NAME = '{item.ENTITY}' AND COMPANY_CODE='{userInfo.company_code}' AND DELETED_FLAG='N'";
if (item.ENTITY_TYPE == "P")
query = $"";
if (item.ENTITY_TYPE == "H")
query = $"SELECT TO_CHAR(CODE) FROM BRD_OTHER_ENTITY WHERE DESCRIPTION = '{item.ENTITY}' AND COMPANY_CODE = '{userInfo.company_code}' AND DELETED_FLAG = 'N'";
entities.Add(new RouteEntityModel
{
ENTITY_Code = _objectEntity.SqlQuery<string>(query).FirstOrDefault(),
ENTITY_TYPE = item.ENTITY_TYPE,
ORDER_NO = sn.ToString()
});
sn++;
}
result.RouteEntityModel = entities;
return result;
}
Finally the controller has following method which imports the excel file and binds the data with model
public JsonResult ImportRouteData(HttpPostedFileBase file)
{
Excel.Application application = new Excel.Application();
try
{
if (file == null || file.ContentLength == 0)
{
return Json(new { TYPE = "error", MESSAGE = "Empty File" }, JsonRequestBehavior.AllowGet);
}
else
{
if (file.FileName.EndsWith("xls") || file.FileName.EndsWith("xlsx"))
{
string paths = Server.MapPath("~/DistributionExcel/Branding/" + file.FileName);
string strMappath = "~/DistributionExcel/Branding/";
string path = System.IO.Path.Combine(Server.MapPath(strMappath), file.FileName);
if (!Directory.Exists(strMappath))
{
Directory.CreateDirectory(Server.MapPath(strMappath));
}
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
file.SaveAs(path);
string sheetName = "Sheet 1";
string filepath = paths;
var excel = new ExcelQueryFactory(filepath);
var worksheetNames = excel.GetWorksheetNames();
if (worksheetNames.ElementAt(0) != sheetName)
{
return Json(new { TYPE = "warning", MESSAGE = "Sheet name mismatched" }, JsonRequestBehavior.AllowGet);
}
var listItems = (from a in excel.Worksheet<RouteImportModel>(sheetName)
where !String.IsNullOrEmpty(a.ROUTE_NAME)
select a).ToList();
var groupedData = listItems.GroupBy(x => x.ROUTE_NAME);
var result = string.Empty;
var inserted = 0;
foreach (var item in groupedData)
{
var group = new RouteGroup
{
Data = item
};
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result == "success")
inserted++;
}
return Json(new { TYPE = "success", MESSAGE = inserted + " items successfully inserted" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { TYPE = "error", MESSAGE = "File format error" }, JsonRequestBehavior.AllowGet);
}
}
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
finally
{
application.Quit();
}
}
The problem is in the line below.
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);
if (result == "success") //THIS LINE IS THE PROBLEM
inserted++;
GetRouteSaveObj return object of type RouteListModel so that compare it to string "success" causing the compiler to try to convert result to string implicitly
I don't know how do you determine if it fails or success so this all I could help.
That's because your are trying to compare RouteListModel with success.Have a look at return type of service method GetRouteSaveObj .
As per your service method ,you should check for null instead of comparing it with string.
Simply convert your following code
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result == "success")
inserted++;
to
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result!=null)
inserted++;

POST data using POSTMAN

so I've been having trouble using the POST method with C# and POSTMAN.
The GET works pretty fine but I'm getting an error on the POST method.
Here's my code:
public SaveProfileResponseDTO SaveProfileQuery(SaveProfileRequestDTO objProfileRequest)
{
SaveProfileResponseDTO objSaveProfileResponse;
try
{
XElement xElement = XElement.Load(Path);
XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
Student.Element("Gender").Value = objProfileRequest.Gender;
xElement.Save(Path);
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Success,
Message = StatusMessages.Success
}
};
}
catch (Exception ex)
{
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Error,
Message = StatusMessages.Error
}
};
}
return objSaveProfileResponse;
}
This is my Controller:
[Route("Profile")]
[HttpPost]
public HttpResponseMessage Profile(SaveProfileRequestModel objSaveProfileRequestModel)
{
StudentManager = new StudentManager();
SaveProfileRequestDTO objSaveProfileRequestDTO = new SaveProfileRequestDTO()
{
Gender = objSaveProfileRequestModel.Gender,
Name = objSaveProfileRequestModel.Name,
StudentID = objSaveProfileRequestModel.StudentID
};
SaveProfileResponseDTO objSavePofileResponse = StudentManager.SaveProfile(objSaveProfileRequestDTO);
SaveProfileResponseModel objSaveProfileResponseModel = new SaveProfileResponseModel()
{
Status = objSavePofileResponse.Status
};
return Request.CreateResponse(HttpStatusCode.OK, objSavePofileResponse);
}
Any help would be appreciated.
I can also provide the GET method code if you want.
Thank you in advance.
XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
This last line will cause a NullReferenceException if there is no student in the XML file matching the ID you're passing in.

Stripe API - C#/.NET List All Customers problems with pagination

this might be a simple answer due to my inexperience with C# and .NET. I have two Stripe Test Accounts. TL:DR; is I am essentially looking for a Customers.all solution.
The source account has all the customer, card, and charge data.
The destination account has the copied card and customer data done by Stripe Support.
I have code that loops through the pulls all the data from the source account. It then finds the customer data from the destination account using the collection of customer/card data from the source. After that it then recreates the charges from the source account into the destination account.
I am able to successfully copy the first 100 charges into the destination account using information from the source account but I am having the hardest time getting the rest of the customers.
This is what I have so far:
public static void GenerateDestinationChargeData()
{
// code to get collection of customer data from destination account
StripeConfiguration.SetApiKey(destinationTestKey);
var customerService = new StripeCustomerService();
IEnumerable<StripeCustomer> customerItems = customerService.List(
new StripeCustomerListOptions()
{
Limit = 100,
//this is what I cannot figure out, eventually to get all of the customers from the destination account
StartingAfter = customerItems.LastOrDefault().Id
}
);
// loop through collection of customers from destination acct to fetch customer charge data from source account
foreach (var i in customerItems)
{
bool isError = false;
var liveChargeService = new StripeChargeService();
StripeConfiguration.SetApiKey(sourceTestKey);
StripeList<StripeCharge> chargeItems = new StripeList<StripeCharge>();
chargeItems = liveChargeService.List(
new StripeChargeListOptions()
{
Limit = 100,
CustomerId = i.Id
}
);
// loop through customer charge data from source and re-create charge data on destination Acct
foreach (var c in chargeItems.Data)
{
StripeConfiguration.SetApiKey(sourceTestKey);
var emailReceipt = "";
Dictionary<string, string> chargeMetaData = new Dictionary<string, string>();
var onBehalfOf = "";
var transferGroup = "";
var chargeDescription = "";
var chargeCaptured = "";
var chargeCurrency = "";
var chargeStatementDescriptor = "";
if (c.ReceiptEmail != null)
{
emailReceipt = c.ReceiptEmail;
}
if (c.Metadata != null)
{
chargeMetaData = c.Metadata;
}
if (c.OnBehalfOf != null)
{
onBehalfOf = c.OnBehalfOf.ToString();
}
if (c.TransferGroup != null)
{
transferGroup = c.TransferGroup;
}
if (c.Description != null)
{
chargeDescription = c.Description;
}
if (c.Captured != null)
{
chargeCaptured = c.Captured.ToString();
}
if (c.Currency != null)
{
chargeCurrency = c.Currency;
}
if (c.StatementDescriptor != null)
{
chargeStatementDescriptor = c.StatementDescriptor;
}
try
{
var chargeOptions = new StripeChargeCreateOptions();
chargeOptions.CustomerId = i.Id;
chargeOptions.ReceiptEmail = emailReceipt;
chargeOptions.Metadata = chargeMetaData;
chargeOptions.Description = chargeDescription;
chargeOptions.Capture = c.Captured;
chargeOptions.Currency = chargeCurrency;
chargeOptions.Amount = c.Amount;
chargeOptions.StatementDescriptor = chargeStatementDescriptor;
StripeChargeService chargeService = new StripeChargeService(destinationTestKey);
StripeCharge stripeCharge = chargeService.Create(chargeOptions);
}
catch (Exception ex)
{
Utility.NotifyDevAdminException("test", ex);
isError = true;
}
if (isError) continue;
}
}
}
Thank you so much :)
Since we cannot do a Customers.all with this current Stripe API, the solution is to set an empty variable and assign it the last Customer ID in the first set of 100 that we get and continue the query from that last assigned value
var lastId = String.Empty;
if (String.IsNullOrEmpty(lastId))
{
StripeConfiguration.SetApiKey(sourceCustomerAccountAPIKey);
customerItems = customerService.List(
new StripeCustomerListOptions(){ Limit = 100 });
}
else
{
StripeConfiguration.SetApiKey(sourceCustomerAccountAPIKey);
customerItems = customerService.List(
new StripeCustomerListOptions() {
Limit = 100,
StartingAfter = lastId });
}
lastId = customerItems.LastOrDefault().Id;

Foreach is not checking properly in mvc when doing a workflow

Am doing a workflow cheching in which i have 2 values and the when the foreach condition is checked only one time it enters the loop and exits out without going to the next one.
public CustomBusinessServices InvokeWorkFlowPermissionBusinessRule(dynamic workFlowImplemented, out string serviceName, out int permissionId)
{
try
{
List<WorkflowEligibilityMapping> workFlowPermissionService = new List<WorkflowEligibilityMapping>();// to handle null values
int current_ControllerId = Convert.ToInt32(workFlowImplemented); //ControllerId
using (var db = new AdminDb())
{
//to select services against this controller
workFlowPermissionService = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId)
select new WorkflowEligibilityMapping
{
Service = permission.Service,
WorkFlowPermissionId = permission.WorkFlowPermissionId
}).ToList();
}
int[] workFlowServiceDetails = workFlowPermissionService.Select(x => x.WorkFlowPermissionId).ToArray();
//to Login userId
var userId = Assyst.PanERP.Common.AppSession.Common.UserID;
/*******************Issue in foreach i think**************************************/
foreach (int workFlowServiceDetail in workFlowServiceDetails)
/*******workFlowServiceDetails have 2 valus********/
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
workFlowServiceDetails have 2 values and the workFlowServiceDetail takes the first one and checks for it.goes through the loop and mapes the role for the first one to the user list at the end and the without checking the for the second vale it moves out of the loop. Please help me to make the loop work for 2 values.Is it some problem in the return part...?
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
If any of the above if statements evaluates to true, your loop will exit without looping through the second item in your array. The reason for this is that you are in your first conditional check do the following:
return new CustomBusinessServices() { strMessage = validationMessage };
And in your second:
return userLists;
The return statement will exit your method, and therefore terminate the foreach as well.
Try building your object first, and after your loop has walked through each item, do a return statement returning your object.

Same function for updating and Saving?

My code to use the function for updating is here and it works also
[HttpPost]
public bool SaveDefCompny(DefCompanyDTO DefCmpny)
{
using (RPDBEntities db = new RPDBEntities())
{
using (TransactionScope trans = new TransactionScope())
{
//the problem is here incase of saving
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
List<DefCompany> list = new List<DefCompany>();
list.Add(UpdateDefCmpnyId);
try
{
foreach (DefCompany DefCmpny1 in list)
{
DefCmpny1.Id = DefCmpny1.Id;
DefCmpny1.ShortName = DefCmpny.ShortName;
DefCmpny1.FullName = DefCmpny.FullName;
DefCmpny1.ContactPerson = DefCmpny.ContactPerson;
DefCmpny1.Address1 = DefCmpny.Address1;
DefCmpny1.CompanyCity = DefCmpny.CompanyCity;
DefCmpny1.CompanyState = DefCmpny.CompanyState;
DefCmpny1.CompanyCountry = DefCmpny.CompanyCountry;
DefCmpny1.ZipPostCode = DefCmpny.ZipPostCode;
DefCmpny1.TelArea = DefCmpny.TelArea;
DefCmpny1.CurrentCurrencyCode = DefCmpny.CurrentCurrencyCode;
db.SaveChanges();
trans.Complete();
}
}
catch (Exception ex)
{
}
}
return false;
}
}
when I try to save instead of updating the line of code
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
gives null value and hence saving fails because record is new and not present in database so how to handle null in case of saving how to use try catch so that when value is null it proceed to saving code that add
How about something along these lines:
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).FirstOrDefault();
if(UpdateDefCmpnyId == null)
{
//insert
//(handle the id however you need to for insert. depending on your setup, you might be able to leave it empty and let the database put it in for you)
}
else
{
//update
//set the id as you do in the question
}

Categories

Resources