I am trying to create functionality to copy data from one order to another. Here is the code that copies the data:
protected void copySeminarIDButton_Click(object sender, EventArgs e)
{
try
{
//show some message incase validation failed and return
String seminarID = this.copySeminarIDText.Text;
Int32 id;
try
{
id = Convert.ToInt32(seminarID);
} catch (Exception e2)
{
return;
}
//copy over all the registration types now for the entered id
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
var seminars = db.seminars.Where(x => x.id == id);
if (seminars.Any())
{
var s = seminars.First();
//Load RegTypes
try
{
var regList = s.seminar_registration_type
.OrderBy(x => x.sort)
.ToList()
.Select(x => new seminarRegistrationTypeListing
{
id = x.id,
amount = x.amount,
description = x.description,
feeTypeId = x.feeTypeId,
method = x.method,
promoCodes = PromoCodesToString(x.xref_reg_type_promo.Select(z => z.promoId).ToList()),
title = x.title,
isPreorder = x.isPreorder,
sort = x.sort
});
this.dlTypes.DataSource = regList;
this.dlTypes.DataBind();
}
catch (Exception ex)
{
Response.Write("RegTypes: " + ex.Message);
}
} else
{
return;
}
}
}
catch (Exception m)
{
}
}
The user will enter a ID of the invoice they want to copy from. The above code copies pull the right data from the invoice and loads it on the page. When i click save the data is being saved.
The problem that is occurring is that the invoice that i copy data from will no longer have the data any more. So basically instead of copying the data its actually moving the data to the new invoice. I want to copy.
Here is my Save code.
private void SaveRegTypes(int seminarId)
{
//Reg Types
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
try
{
var s = db.seminars.Where(x => x.id == seminarId).First();
var msg = "alert('Saving:" + seminarId + "');";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", msg, true);
this.copySeminarIDText.Text = msg;
//s.seminar_registration_type.Clear();
foreach (DataListItem dli in this.dlTypes.Items)
{
String sId = ((HiddenField)dli.FindControl("hdnId")).Value;
var reg = new seminar_registration_type();
if ((sId != "") && (sId != "0"))
{
Int32 id = Convert.ToInt32(sId);
reg = db.seminar_registration_type.Where(x => x.id == id).Single();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", "alert('hidded field id is empty.');", true);
}
else
{
db.seminar_registration_type.Add(reg);
}
reg.feeTypeId = Convert.ToInt32(((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Value);
reg.amount = Convert.ToDecimal(((TextBox)dli.FindControl("txtPrice")).Text);
reg.title = ((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Text;
reg.description = ((TextBox)dli.FindControl("txtRegDesc")).Text;
reg.method = Convert.ToInt32(((DropDownList)dli.FindControl("ddlDeliveryMethod")).Text);
reg.promocode = null;
reg.isPreorder = Convert.ToBoolean(((CheckBox)dli.FindControl("chkPreorder")).Checked);
reg.sort = 1;
reg.seminarId = seminarId;
string sort = ((TextBox)dli.FindControl("txtRTSort")).Text;
try
{
reg.sort = Convert.ToInt32(sort);
}
catch (Exception ex) { }
//Do Promo Codes
Repeater rptPromocodes = (Repeater)dli.FindControl("rptPromoCodesList");
reg.xref_reg_type_promo.Clear();
foreach (RepeaterItem ri in rptPromocodes.Items)
{
try
{
Int32 id = Convert.ToInt32(((HiddenField)ri.FindControl("hdnCodeId")).Value);
DateTime? expires = null;
try
{
HiddenField exp = (HiddenField)ri.FindControl("hdnExpirationDate");
if (!String.IsNullOrWhiteSpace(exp.Value))
expires = Convert.ToDateTime(((HiddenField)ri.FindControl("hdnExpirationDate")).Value);
}
catch (Exception ex) { }
var code = db.promo_code.Where(x => x.id == id).First();
reg.xref_reg_type_promo.Add(new xref_reg_type_promo
{
expiration = expires,
promoId = code.id
});
}
catch (Exception ex) { }
}
db.SaveChanges();
((HiddenField)dli.FindControl("hdnId")).Value = reg.id.ToString();
}
}
catch (Exception ex)
{
String err = ex.Message;
}
}
}
Related
Have a quote application, which we fill the data and send from source system to receiver system. That receiver system will be sending status of that quote(Success/Failed) as Acknowledgement to source system. We have an option to revise the same quote. whenever we revise the quote, the Status is inherited from previous quote. we need to clear the latest revision's status. which is not happening. but it clears previous revision's status. Could anyone help me.
if (plm == "PLM")
{
if (id.Revision != 0)
{
var javascriptSerializer = new JavaScriptSerializer();
var urn = line.CustomProperties?.FirstOrDefault(k => k.Key.ToLower() == "urn")?.Value;
oRecordLog.WriteToLogFile("Updating DBValue");
//initilizing document store object to query the documents from database.
IDocumentStore ravenDB = new DocumentStore { Url = "http://localhost:8072", DefaultDatabase = "Configit.Quote" }.Initialize();
try
{
List<Document> docs;
using (var session = ravenDB.OpenSession())
{
oRecordLog.WriteToLogFile("Opened RavenDB session");
//getting the URN value.
var javaScriptSerializer = new JavaScriptSerializer();
string urnString = urn;
ModelKeyValuePair urnKeyValue = new ModelKeyValuePair();
urnKeyValue.Key = "URN";
urnKeyValue.Value = javaScriptSerializer.Serialize(urnString);
//wait for 5 seconds before the next query
docs = session.Query<Document>().Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5))).Where(x => x.Lines.Any(l => l.Properties.Any(ID => ID == urnKeyValue))).ToList();
try
{
oRecordLog.WriteToLogFile("docs " + docs.Count);
//processing one by one document from RavenDB.
foreach (var doc in docs)
{
string quoteGuid = null;
if (doc.LinesCount > 0)
{
int lineCnt = doc.LinesCount;
// processing each line in the docuement getting the quoteID
foreach (var quoteline in doc.Lines)
{
if ((quoteline.Properties.ContainsKey("Urn")) || (quoteline.Properties.ContainsKey("URN")) || (quoteline.Properties.ContainsKey("urn")))
{
Guid lGuid = quoteline.LineId;
var quote_ForID = _quoteStorage.GetQuote(new QuoteRevisionId(id.QuoteId, id.Revision));
var urn_ForQuoteId = quoteline.Properties?.FirstOrDefault(k => k.Key == "URN")?.Value;
if (GetUniqueRefnum(quote_ForID, quoteline) == urn_ForQuoteId)
{
quoteGuid = doc.DocumentId.ToString();
oRecordLog.WriteToLogFile("quoteGuid " + quoteGuid);
var TransferStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "TransferStatus");
var PLMDetailedStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "PLMDetailedStatus");
TransferStatus.Value = "";
PLMDetailedStatus.Value = "";
}
}
}
}
else
{
oRecordLog.WriteToLogFile("Quote ID not found");
}
}
session.SaveChanges();
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
}
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
else
{
oRecordLog.WriteToLogFile("This is new quote");
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
}
I am writing an asp.net web API using Visual Studio 2019. When I write as in the example below, Visual Studio recommends me making the method static. So I followed the suggestions and made all methods of the Web API static. Is this correct? What is the advantage if it is correct and what is the disadvantage if it is wrong?
Thank you...
Severity Code Description Project File Line Suppression State
Message CA1822 Member AdresleriGetir does not access instance data and can be marked as static (Shared in VisualBasic) Devriye.WebApi**
My method:
[HttpPost]
public static Adres[] AdresleriGetir([FromBody]GirisParametresi girisParametresi)
{
if (girisParametresi != null)
{
string query = #"SELECT * FROM ADRESLER WHERE AKTIF=1";
Cagri cagri = new Cagri()
{
Proje = "Devriye.WebApi",
Modul = "AdresController",
Metot = "AdresGetir",
Nesne = new JavaScriptSerializer().Serialize(girisParametresi)
};
Log log = new Log(null, cagri, girisParametresi.Oturum);
using (DataTable dataTable = DataAccessLayer.VerileriGetir(query, null, log))
{
List<Adres> adresler = new List<Adres>();
if (dataTable.Rows.Count > 0)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Adres adres = new Adres();
try { adres.Cadde = Convert.ToString(dataTable.Rows[i]["Cadde".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.EklenmeTarihi = Convert.ToDateTime(dataTable.Rows[i]["EklenmeTarihi".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.ID = Convert.ToInt32(dataTable.Rows[i]["ID".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Il = Convert.ToString(dataTable.Rows[i]["Il".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Ilce = Convert.ToString(dataTable.Rows[i]["Ilce".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.KapiNo = Convert.ToString(dataTable.Rows[i]["KapiNo".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Mahalle = Convert.ToString(dataTable.Rows[i]["Mahalle".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.PostaKodu = Convert.ToInt32(dataTable.Rows[i]["PostaKodu".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
try { adres.Sokak = Convert.ToString(dataTable.Rows[i]["Sokak".ToUpperInvariant()], WebApiConfig.CultureInfo); } catch (Exception ex) { if (log != null) { log.Hata = new Hata() { Aciklama = ex.Message, HataKodu = 997 }; Task.Run(() => DataAccessLayer.LogKaydet(log)); } }
adresler.Add(adres);
}
return adresler.ToArray();
}
else
{
return null;
}
}
}
else
{
return null;
}
}
This function doesn't access any instance data or call any instance methods.
I've had similar questions about R# wanting to convert this type of function to static. See this SO question for some reasons. From the accepted answer in the link;
It makes me ask myself if the method in question should actually be
part of the type or not. Since it doesn't use any instance data, you
should at least consider if it could be moved to its own type. Is it
an integral part of the type, or is it really a general purpose
utility method?
If it does make sense to keep the method on the specific type, there's
a potential performance gain as the compiler will emit different code
for a static method.
I have a base save changes function but its not working its not returning an error just nothing get's written to the database.
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = new Patient();
_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
_patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = (int)dpRace.SelectedValue;
_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
_patient.Language = (int)dpLanguages.SelectedValue;
_patient.AlertNote = txtPatientNotes.Text;
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = dpGender.Text.Substring(0, 1);
_patient.PatientID = txtPatientId.Text;
txtPatientFirstName.Text = _patient.FirstName;
txtPatientLastName.Text = _patient.LastName;
if(updateOrSave == false) // IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.
SourceDal.AddToPatient(_patient);
SourceDal.SaveChanges();
My Source dal is made up of functions which which is inherits context base which has the following
public abstract int SaveChanges();
protected int SaveChanges(System.Data.Entity.Core.Objects.ObjectContext context)
{
try
{
int i = context.SaveChanges();
if (i == 0)
return 0;
return 1;
}
catch (Exception ex)
{
throw new EntityContextException("SaveChanges failed.", ex);
}
}
There is no error so dont no what is going wrong i declare SourceDal as such
SourceContext SourceDal = new SourceContext();
This is my save cahnges that is on the sourcedal
public override int SaveChanges()
{
try
{
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
return myContext.SaveChanges();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
Edit 2
I have even tried the following and still it has not save the patient record the AddToPaient works fine
public void SavePatient(Patient _patient)
{
try {
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
myContext.Entry(_patient).State = System.Data.Entity.EntityState.Modified;
myContext.SaveChanges();
}
}
catch (Exception EX)
{ }
}
For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you
I have now solved this issue. I have left the original question / code in place for comparison.
* SOLUTION *
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
I am trying to update data on an existing ParseObject using C# in Unity3D. My code is as follows:
Original code:
public static void saveUserData(string emailAddress) {
ParseObject userData = new ParseObject("userData");
ParseObject userLevelData = new ParseObject("levelData");
userData["playerName"] = emailAddress;
try {
ParseQuery<ParseObject> parseData = ParseObject.GetQuery("userData").WhereEqualTo("playerName", userData["playerName"]);
parseData.FirstAsync().ContinueWith(t => {
if(t.IsFaulted) {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
userLevelData["level"] = GameStatus.currentUser.level;
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = -1;
userData.SaveAsync();
userLevelData.SaveAsync();
} else if(!t.IsCanceled) {
userData = t.Result;
try {
userData.SaveAsync().ContinueWith(t2 => {
userData["level"] = GameStatus.currentUser.level;
userData["highestLevel"] = GameStatus.currentUser.highestLevel;
userData["currentLevelTime"] = GameStatus.currentUser.currentLevelTime;
userData["version"] = UserData.currentUserDataVersion;
ParseQuery<ParseObject> levelData = ParseObject.GetQuery("levelData").WhereEqualTo("playerName", userData["playerName"]).WhereEqualTo("level", GameStatus.currentUser.level);
levelData.FirstAsync().ContinueWith(t3 => {
if(t3.IsFaulted) {
userLevelData["level"] = userData["level"];
userLevelData["playerName"] = emailAddress;
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = GameStatus.currentUser.currentLevelData.time;
userLevelData.SaveAsync();
} else if(!t3.IsCanceled) {
userLevelData = t3.Result;
int timeVal = Convert.ToInt32(userLevelData["time"]);
if(timeVal == -1 || GameStatus.currentUser.currentLevelData.time < timeVal) {
try {
userLevelData.SaveAsync().ContinueWith(t4 => {
userLevelData["date"] = DateTime.Now;
userLevelData["time"] = DateTime.Now.Ticks;
userLevelData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
}
});
userData.SaveAsync();
});
} catch(Exception e) {
Debug.LogException(e);
}
}
});
} catch(Exception e) {
Debug.LogException(e);
}
}
Now, I get an output stating the user is found, and creating a user if it's not found works OK. The issue I have is that, although I've specified a userFound bool, the if(userFound) nest is never called.
Can anyone see what I've done (or haven;t done) or am I totally going about this the wrong way?
Any help appreciated.