I am trying to insert it into the database via LINQ-SQL. I am trying the following
using(DataContext obj = new DataContext())
{
mdc_meters_data data = new mdc_meters_data();
data.cust_id = cust_id;
data.device_id = Convert.ToString(device_id);
data.kwh = Convert.ToString(e_val);
data.voltage_p1 = Convert.ToString(a_vol_val);
data.voltage_p2 = Convert.ToString(b_vol_val);
data.voltage_p2 = Convert.ToString(c_vol_val);
data.current_p1 = Convert.ToString(a_curr_val);
data.current_p2 = Convert.ToString(b_curr_val);
data.current_p3 = Convert.ToString(c_curr_val);
data.data_date_time = Convert.ToDateTime(theDate.ToString(format));
data.d_type = Convert.ToString(d_type);
data.pf1 = Convert.ToString(a_pf_val);
data.pf2 = Convert.ToString(b_pf_val);
data.pf3 = Convert.ToString(c_pf_val);
data.p_id = p_id;
// executes the commands to implement the changes to the database
obj.SubmitChanges();
}
The error I am getting is
'DataContext' does not contain a definition for 'SubmitChanges' and no accessible extension method 'SubmitChanges' accepting a first argument of type 'DataContext' could be found
Update 1
I was doing it wrong so I tried to do it with my class which inherits DbContext class. But for an unknown reason, it's still not inserting the data
using(mdc_dbEntities obj = new mdc_dbEntities())
{
mdc_meters_data data = new mdc_meters_data();
data.cust_id = cust_id;
data.device_id = Convert.ToString(device_id);
data.kwh = Convert.ToString(e_val);
data.voltage_p1 = Convert.ToString(a_vol_val);
data.voltage_p2 = Convert.ToString(b_vol_val);
data.voltage_p2 = Convert.ToString(c_vol_val);
data.current_p1 = Convert.ToString(a_curr_val);
data.current_p2 = Convert.ToString(b_curr_val);
data.current_p3 = Convert.ToString(c_curr_val);
data.data_date_time = Convert.ToDateTime(theDate.ToString(format));
data.d_type = Convert.ToString(d_type);
data.pf1 = Convert.ToString(a_pf_val);
data.pf2 = Convert.ToString(b_pf_val);
data.pf3 = Convert.ToString(c_pf_val);
data.p_id = p_id;
// executes the commands to implement the changes to the database
obj.SaveChanges();
}
Related
We have a custom transaction table setup in netsuite that I'm wanting to push entries to through SOAP service for netsuite but all the example i've found havent worked. The code that i've been playing around with responds with "Invalid custom transaction type identifier." and not sure how to correct that. Any help is apprecited!
URL to a manually entered transaction: app/accounting/transactions/cutrsale.nl?id=744512&customtype=107&whence=
So i'm assuming the internalID is 107
CustomTransaction myCustomTrxn = new CustomTransaction();
myCustomTrxn.externalId = "1055A";
// Create a RecordRef to identify the custom transaction type
RecordRef myCustTrxnType = new RecordRef();
myCustTrxnType.type = RecordType.customTransactionType;
myCustTrxnType.typeSpecified = true;
myCustTrxnType.internalId = "107";
myCustomTrxn.tranType = myCustTrxnType;
// Create a sublist and add two lines.
CustomTransactionLineList myLineList = new CustomTransactionLineList();
myLineList.customTransactionLine = new CustomTransactionLine[2];
myCustomTrxn.lineList = myLineList;
myLineList.customTransactionLine[0] = new CustomTransactionLine();
RecordRef myAccount = new RecordRef();
myAccount.type = RecordType.account;
myAccount.typeSpecified = true;
myAccount.internalId = "9";
myLineList.customTransactionLine[0].account = myAccount;
myLineList.customTransactionLine[0].amount = 1000;
myLineList.customTransactionLine[0].amountSpecified = true;
myLineList.customTransactionLine[1] = new CustomTransactionLine();
RecordRef myAccount2 = new RecordRef();
myAccount2.type = RecordType.account;
myAccount2.typeSpecified = true;
myAccount2.internalId = "10";
myLineList.customTransactionLine[1].account = myAccount2;
myLineList.customTransactionLine[1].amount = 2000;
myLineList.customTransactionLine[1].amountSpecified = true;
var response = await service.addAsync(Shared.createTokenPassport(), null, null, null, myCustomTrxn);
return response;
I was able to add a custom record into netsuite via soap and c# as well as adding files into netsuite. I'm just stuck on how i can make a reference so the attachment shows up linked to the custom record i've created. I thought adding the recordRef internalID would do the trick but is not working. Here is my code below for both stepsk, then code on trying to make the reference but i get an error saying customrecord type is invalid?
Adding custom record
NetSuitePortTypeClient service = new NetSuitePortTypeClient(NetSuitePortTypeClient.EndpointConfiguration.NetSuitePort, "https://4249999-sb1.suitetalk.api.netsuite.com/services/NetSuitePort_2022_1");
CustomRecord customRecord = new CustomRecord();
customRecord.name = "Frank Dux";
RecordRef recordType = new RecordRef();
recordType.internalId = "665"; // // Record Type's internal ID (Setup > Customization > Record Types > Basic Record Type (Internal ID=14)
recordType.type = RecordType.customRecord;
recordType.typeSpecified = true;
customRecord.recType = recordType;
//customRecord.internalId = "2"; // internal id of the custom record you want to update
StringCustomFieldRef stringCustomFieldRef = new StringCustomFieldRef();
stringCustomFieldRef.scriptId = "custrecord_fs_afe";
stringCustomFieldRef.value = "AFE name";
CustomFieldRef[] customFieldRef = new CustomFieldRef[1];
customFieldRef[0] = stringCustomFieldRef;
customRecord.customFieldList = customFieldRef;
var response = await service.addAsync(Shared.createTokenPassport(), null, null, null, customRecord);
Adding the file attachment
NetSuiteWSSB20221.File myFile = new NetSuiteWSSB20221.File();
myFile.name = "time_attach303.pdf";
myFile.attachFrom = FileAttachFrom._computer;
myFile.attachFromSpecified = true;
myFile.fileType = MediaType._PDF;
byte[] data;
var _fileUpload = _ctx.NTGPortalFile.SingleOrDefault(aa => aa.NTGPortalFileId == "563451d8-54e7-3344-9033-ba723b299b49");
MemoryStream ms = new MemoryStream(_fileUpload.FileContents);
data = ms.ToArray();
RecordRef recRef = new RecordRef();
recRef.internalId = "303";
myFile.mediaFile = recRef;
RecordRef folderRef = new RecordRef();
folderRef.internalId = "17";
myFile.folder = folderRef;
myFile.content = data;
var fileresponse = await service.addAsync(Shared.createTokenPassport(), null, null, null, myFile);
Adding attaching the file to the custom record attempt..
//file record
RecordRef recFile = new RecordRef();
recFile.internalId = fileResponse.writeResponse.baseRef.internalId;
recFile.type = RecordType.file;
recFile.typeSpecified = true;
//custom record
RecordRef recCusRec = new RecordRef();
recCusRec.internalId = cusRecordResponse.writeResponse.baseRef.internalId;
recCusRec.type = RecordType.customRecord;
recCusRec.typeSpecified = true;
//attach class
AttachBasicReference attachBasicRef = new AttachBasicReference();
attachBasicRef.attachedRecord = recFile;
attachBasicRef.attachTo = recCusRec;
var fileAttachResponse = await service.attachAsync(Shared.createTokenPassport(), null, null, null, attachBasicRef);
I have an attribute that I'd like to add for faceting: ApprovalFL. When I add the facet in the Algolia dashboard, it works fine until I have to reindex which ends up deleting my facets in the dashboard for some reason. I was thinking, maybe adding the attribute in my code would resolve that. I found the documentation about this step here: https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting/
Here's the C# example they provide:
index.SetSettings(
JObject.Parse(#"{""attributesForFaceting"":[""author"",""filterOnly(category)"",""searchable(publisher)""]}")
);
If I understand correctly, this code needs to go in my backend reindexing code (found in my AdminController.cs):
public async Task<ActionResult> ReIndexData()
{
var algoliaArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllAccountInfoes());
var algoliaUnaffiliatedArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllUnaffiliatedAccountInfo());
var algoliaSongModels = Tools.BuildAlgoliaSongModels(EntityDataAccess.GetAllAcceptedSongs());
var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
var unaffiliatedArtistIndexHelper = HttpContext.Application.Get("UnaffiliatedArtist") as IndexHelper<ArtistAlgoliaModel>;
var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
await artistIndexHelper.OverwriteIndexAsync(algoliaArtistModels);
await unaffiliatedArtistIndexHelper.OverwriteIndexAsync(algoliaUnaffiliatedArtistModels);
await songIndexHelper.OverwriteIndexAsync(algoliaSongModels);
return View("AlgoliaReIndexData");
}
However, I don't think I put index.setSettings in this block of code, what is the best way to set this attribute for faceting in my backend code? The ApprovalFL attribute is stored in my Song indices.
Possibly it should go somewhere here in my Tools.cs?
public static SongAlgoliaModel BuildAlgoliaSongModel(Song song)
{
var model = new SongAlgoliaModel();
var album = EntityDataAccess.GetAlbumByID(song.AlbumID);
model.AccountImageURL = album.AccountInfo.ImageURL;
model.AccountInfoID = album.AccountInfoID;
model.AccountType = album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = song.AlbumID;
model.AlbumName = album.AlbumName;
model.ApprovalFL = song.ApprovalFL;
model.Artist = album.AccountInfo.DisplayName;
model.BPM = song.BPM;
model.Duration = song.Duration;
model.FeaturedArtist = song.Artist;
model.FreeFL = album.FreeFL;
model.ImageURL = album.ImageURL;
model.iTunesURL = album.iTunesURL;
model.LabelName = album.LabelName;
model.LicenseFL = album.LicenseFL;
model.SongID = song.SongID;
model.Title = song.Title;
model.UploadDate = song.UploadDate;
model.URL = song.URL;
model.UserID = album.AccountInfo.UserID;
return model;
}
public static List<SongAlgoliaModel> BuildAlgoliaSongModels(AccountInfo accountInfo)
{
var list = new List<SongAlgoliaModel>();
var songs = EntityDataAccess.GetSongsByUserID(accountInfo.UserID).Where(x => x.ApprovalFL == true).ToList();
foreach(var item in songs)
{
var model = new SongAlgoliaModel();
model.AccountImageURL = item.Album.AccountInfo.ImageURL;
model.AccountInfoID = item.Album.AccountInfoID;
model.AccountType = item.Album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = item.AlbumID;
model.AlbumName = item.Album.AlbumName;
model.ApprovalFL = item.ApprovalFL;
model.Artist = item.Album.AccountInfo.DisplayName;
model.BPM = item.BPM;
model.Duration = item.Duration;
model.FeaturedArtist = item.Artist;
model.FreeFL = item.Album.FreeFL;
model.ImageURL = item.Album.ImageURL;
model.iTunesURL = item.Album.iTunesURL;
model.LabelName = item.Album.LabelName;
model.LicenseFL = item.Album.LicenseFL;
model.SongID = item.SongID;
model.Title = item.Title;
model.UploadDate = item.UploadDate;
model.URL = item.URL;
model.UserID = item.Album.AccountInfo.UserID;
list.Add(model);
}
return list;
}
OK for those using C# .NET it's as simple as adding it to your Global.asax.cs for example for me:
var songIndexHelper = new IndexHelper<SongAlgoliaModel>(algoliaClient, "Song", "SongID");
songIndexHelper.SetSettings(JObject.Parse(#"{""attributesForFaceting"":[""ApprovalFL""]}"));
Why do you have to re-index by the way? Best practice is to set up your index only initially.
I want to get my linq query result back as json format. I have been searching for hours.
Here is my code :
public IEnumerable<callersW> GetAllCallersF()
{
testCDREntities1 context = this.CurrentDataSource;
var query = (
from oneCaller in CurrentDataSource.TestTables
select new
{
Created = oneCaller.Created,
Answered = oneCaller.Answered,
Destroyed = oneCaller.Destroyed,
CallerID = oneCaller.CallerId,
CalledID = oneCaller.CalledId,
DisconnectionCode = oneCaller.DisconnectionCode,
RTP_Caller_G107MOS = oneCaller.RTP_Caller_G107MOS,
RTP_Caller_LostPackets = oneCaller.RTP_Caller_LostPackets,
RTP_Caller_MaxRfc3550Jitter = oneCaller.RTP_Caller_MaxRfc3550Jitter,
RTP_Caller_MeanRfc3550Jitter = oneCaller.RTP_Caller_MeanRfc3550Jitter,
RTP_Called_G107MOS = oneCaller.RTP_Called_G107MOS,
RTP_Called_LostPackets = oneCaller.RTP_Called_LostPackets,
RTP_Called_MaxRfc3550Jitter = oneCaller.RTP_Called_MaxRfc3550Jitter,
RTP_Called_MeanRfc3550Jitter = oneCaller.RTP_Called_MeanRfc3550Jitter,
}).ToList()
.Select(x => new callersW
{
Created = Convert.ToDateTime(x.Created),
Answered = Convert.ToDateTime(x.Answered),
Destroyed = Convert.ToDateTime(x.Destroyed),
CallerID = x.CallerID,
CalledID = x.CalledID,
DisconnectionCode = Convert.ToInt32(x.DisconnectionCode),
RTP_Caller_G107MOS = Convert.ToDouble(x.RTP_Caller_G107MOS),
RTP_Caller_LostPackets = Convert.ToDouble(x.RTP_Caller_LostPackets),
RTP_Caller_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MaxRfc3550Jitter),
RTP_Caller_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Caller_MeanRfc3550Jitter),
RTP_Called_G107MOS = Convert.ToDouble(x.RTP_Called_G107MOS),
RTP_Called_LostPackets = Convert.ToDouble(x.RTP_Called_LostPackets),
RTP_Called_MaxRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MaxRfc3550Jitter),
RTP_Called_MeanRfc3550Jitter = Convert.ToDouble(x.RTP_Called_MeanRfc3550Jitter)
}).ToList();
return query;
}
Can somebody help me with this ?
Add to your project JSON.NET and serialize object eg:
string json = JsonConvert.SerializeObject(query);
More examples here.
C#, Linq2Sql, .NET 2.0, SQL 2005 Express
When I run the following code I get a
InvalidCastException unable to cast of type System.Byte[] to System.String
This does not occur on all rows in the table i.e. this code runs fine soemtimes.
I checked there are no columns in the table that linq declares as SYstem.Byte[]
The stack trace says the exception occurs on the linq statement and when I F11
into the code the GetProject is never called the exception occurs before this method
is called.
So I think it is Linq framework bug.
This has got me stumped? any ideas?
[code]
public Project GetProject(int id)
{
var project = (from row in _dbctx.Projects
where row.ProjectID == id
select row).SingleOrDefault();
Project proj = GetProject(project);
return proj;
}
private Project GetProject(TBRServices.Domain.TBR.DataContext.Project sqlproject)
{
Project project = new Project();
project.ProjectID = sqlproject.ProjectID;
project.ProjectName = sqlproject.ProjectName;
project.ProjectDescription = sqlproject.ProjectDescription;
project.ClientID = sqlproject.ClientID;
project.PurchaseOrderNumber = sqlproject.PurchaseOrderNumber;
project.ProjectTotalBillingEstimate = sqlproject.ProjectTotalBillingEstimate;
project.EmployeeID = sqlproject.EmployeeID;
project.ProjectBeginDate = sqlproject.ProjectBeginDate.ToString();
project.ProjectEndDate = sqlproject.ProjectEndDate.ToString();
project.Active = sqlproject.Active;
project.InclGST = sqlproject.InclGST;
project.ContractRate = sqlproject.ContractRate;
project.MarginRate = sqlproject.MarginRate;
project.Notes = sqlproject.Notes;
project.PayrollTax = sqlproject.PayrollTax;
project.EmployeeReference = sqlproject.EmployeeReference;
project.PayReference = sqlproject.PayReference;
project.ProjectLocation = sqlproject.ProjectLocation;
project.ContractTypeID = sqlproject.ContractTypeID;
project.DoNotCalcMarginOrGST = sqlproject.DoNotCalcMarginOrGST;
project.ConvertToInvoice = sqlproject.ConvertToInvoice;
project.AuthFirstname = sqlproject.AuthFirstname;
project.AuthLastname = sqlproject.AuthLastname;
project.AuthEmail = sqlproject.AuthEmail;
project.CapturedDocumentType = sqlproject.CapturedDocumentType;
project.TimesheetProcessingType = sqlproject.TimesheetProcessingType;
project.TimesheetFrequency = sqlproject.TimesheetFrequency;
project.AggregateTimesheet = sqlproject.AggregateTimesheet;
project.AggregateAutomatically = sqlproject.AggregateAutomatically;
project.BusProcEmpCut = sqlproject.BusProcEmpCut;
project.BusProcAgencyCut = sqlproject.BusProcAgencyCut;
project.SendCopyTimesheet = sqlproject.SendCopyTimesheet;
project.TimesheetRecipient1 = sqlproject.TimesheetRecipient1;
project.TimesheetRecipient2 = sqlproject.TimesheetRecipient2;
project.SendCopyInvoice = sqlproject.SendCopyInvoice;
project.PublishedOn = sqlproject.PublishedOn.ToString();
project.SendAggTimesheetsWhenReceived = sqlproject.SendAggTimesheetsWhenReceived;
project.AuthoriseInvoice = sqlproject.AuthoriseInvoice;
project.HourlyDailyMthly = sqlproject.HourlyDailyMthly;
project.EmployeeCategory = sqlproject.EmployeeCategory;
project.AgencyRate = sqlproject.AgencyRate;
project.ConsultantID = sqlproject.ConsultantID;
project.SendCopyInvoiceEmployee = sqlproject.SendCopyInvoiceEmployee;
project.UseClientDetailsForTimesheet = sqlproject.UseClientDetailsForTimesheet;
project.FaxedTimesheet = sqlproject.FaxedTimesheet;
project.TimesheetEditable = sqlproject.TimesheetEditable;
project.IncludeInReport = sqlproject.IncludeInReport;
project.SendLogonEmail = sqlproject.SendLogonEmail;
project.NoticePeriodID = sqlproject.NoticePeriodID;
project.ManagerCanViewPaidUnpaid = sqlproject.ManagerCanViewPaidUnpaid;
project.LesterSalesStaff = sqlproject.LesterSalesStaff;
project.IncludeSalesReport = sqlproject.IncludeSalesReport;
project.CurrencyAccount = sqlproject.CurrencyAccount;
project.LeaveMustBeAuthorisedTimesheet = sqlproject.LeaveMustBeAuthorisedTimesheet;
project.LeaveMustBeAuthorisedLeaveForm = sqlproject.LeaveMustBeAuthorisedLeaveForm;
project.DefaultHoursWorkedWeek = sqlproject.DefaultHoursWorkedWeek;
project.DefaultHoursWorkedDay = sqlproject.DefaultHoursWorkedDay;
project.AccruedLeaveStartDate = sqlproject.AccruedLeaveStartDate.ToString();
project.AllowLeaveMoreThanAccrued = sqlproject.AllowLeaveMoreThanAccrued;
project.IsPaidASalary = sqlproject.IsPaidASalary;
project.AgencyID = sqlproject.AgencyID;
project.SendEmailToManagerToOKLeave = sqlproject.SendEmailToManagerToOKLeave;
project.SpecialPayrollNotes = sqlproject.SpecialPayrollNotes;
project.SpecialInvoicingNotes = sqlproject.SpecialInvoicingNotes;
project.InvoiceTermsMessage = sqlproject.InvoiceTermsMessage;
project.AuthManagerPhone = sqlproject.AuthManagerPhone;
project.LMF = sqlproject.LMF;
project.LMFPercent = sqlproject.LMFPercent;
project.LMFInclInPayRate = sqlproject.LMFInclInPayRate;
project.LMFOnTop = sqlproject.LMFOnTop;
project.AgencyComm = sqlproject.AgencyComm;
project.AgencyCommPercent = sqlproject.AgencyCommPercent;
project.AgencyCommInclInPayRate = sqlproject.AgencyCommInclInPayRate;
project.AgencyCommOnTop = sqlproject.AgencyCommOnTop;
project.PayRateInclMargin = sqlproject.PayRateInclMargin;
project.MarginRatePercent = sqlproject.MarginRatePercent;
project.MarginRateGST = sqlproject.MarginRateGST;
project.MarginRateInclInPayRate = sqlproject.MarginRateInclInPayRate;
project.MarginRateOnTop = sqlproject.MarginRateOnTop;
project.PayRateInclSuper = sqlproject.PayRateInclSuper;
project.PayrollTaxAmount = sqlproject.PayrollTaxAmount;
project.PayrollTaxPercent = sqlproject.PayrollTaxPercent;
project.PayrollTaxInclInPayRate = sqlproject.PayrollTaxInclInPayRate;
project.PayrollTaxOnTop = sqlproject.PayrollTaxOnTop;
project.TypeOfArrangement = sqlproject.TypeOfArrangement;
project.ParameterRequired = sqlproject.ParameterRequired;
project.SpecialPayrollEnabled = sqlproject.SpecialPayrollEnabled;
project.ClientContactUsedReceiptOfInvoiceID = sqlproject.ClientContactUsedReceiptOfInvoiceID;
project.ExcludeEmpNameOnInvoice = sqlproject.ExcludeEmpNameOnInvoice;
project.BPForReporting = sqlproject.BPForReporting;
project.UseGemteqInvoiceFormat = sqlproject.UseGemteqInvoiceFormat;
project.TreatPayrollDetailsSameAsBP = sqlproject.TreatPayrollDetailsSameAsBP;
return project;
}
[/code]
Check the answer to a similar SO question. It will not be the exact answer but may help you find the problem in your query -
Problem with Linq to SQL
unable to cast of type System.Byte[] to System.String
Indicates that a property in sqlproject is stored as byte[] while the corresponding property in project is a string