LINQ how to generate csv file section - vb.net

I got the problem generating csv file based on the section. I currently using LinqToCsv dll to generate the file. How do I generate the file by section. Please help. Thanks.
Currenly I have 3 section
Header Section
Detail Section
Footer Section
Here my codes.
TTMSEntities DB = new TTMSEntities();
CsvFileDescription outputFileDescription = new CsvFileDescription();
outputFileDescription.NoSeparatorChar = false;
outputFileDescription.FirstLineHasColumnNames = true;
outputFileDescription.FileCultureName = "en-US";
List<HeaderRec> list1 = new List<HeaderRec>();
HeaderRec header = new HeaderRec();
header.RecordType = "";
header.RetailerID = "";
header.FileDate = "";
header.FileSequence = "";
header.LastTransRef = "";
list1.Add(header);
var Data = (from p in DB.TT_TNG_KFC_TRANSACTION_UPLOAD
select new DetailRec
{
RecordType = "D",
TransIDType ="AA"
});
List<FooterRec> list2 = new List<FooterRec>();
FooterRec footer = new FooterRec();
footer.RecordType = "T";
footer.TotalAmount = "100";
list2.Add(footer);
CsvContext cc = new CsvContext();
cc.Write(Data, "TestData.csv", outputFileDescription);
How to I concat the List ?

Related

How to process batchUpdate and copy from one spreadsheet into another using Google Sheets API

Link to original question where I found the below script: How to batch-copy range with Google Sheets Api
Question: How do I modify the below to write into a different spreadsheetId? I've Googled everything I can and can only find examples where the copyPaste occurs within the same SpreadsheetID.
function Test_Copy() {
var spreadsheetId = "1hLXq9zq-tAaGpPtGiY6859h4oKxIbNimxCHPPZOzdE0";
var sheetId = "1792457718";
var sheetIdd = "760382355";
var rangeFrom = Sheets.newGridRange();
rangeFrom.sheetId = sheetId;
rangeFrom.startRowIndex = 0;
rangeFrom.endRowIndex = 23637;
rangeFrom.startColumnIndex = 0;
rangeFrom.endColumnIndex = 23;
var rangeTo = Sheets.newGridRange();
rangeTo.sheetId = sheetIdd;
rangeTo.startRowIndex = 0;
rangeTo.endRowIndex = 23637;
rangeTo.startColumnIndex = 0;
rangeTo.endColumnIndex = 23;
var copyPasteRequest = Sheets.newCopyPasteRequest();
copyPasteRequest.destination = rangeTo;
copyPasteRequest.source = rangeFrom;
copyPasteRequest.pasteType = "PASTE_VALUES";
copyPasteRequest.pasteOrientation = "NORMAL";
var resource = Sheets.newBatchUpdateSpreadsheetRequest();
//Create request object
var request = Sheets.newRequest();
request.copyPaste = copyPasteRequest;
resource.requests = [request];
var res = Sheets.Spreadsheets.batchUpdate(resource , spreadsheetId);
//Logger.log(res.replies);
//Logger.log(res.spreadsheetId);
}

Authentication lost Google app script

I have created a a google app script that create a pdf from a google sheet and send it via email.
I have three script that work perfectly. But with the fourth script (identical to the other)I lost always the authorization after about one - two hours.
Has someone the same problem?
Thanks
Pasquale
Attached code. I use a trigger to lunch code every time the form is submitted.
// When Form Gets submitted
function onFormSubmit(e) {
var docTemplate = "1mI4SQQe4muuW386jgzkxBlZBWuH0OBRdbz1hItOPjK4";
var docName = "DDT";
var ss = SpreadsheetApp.openById("1HzZFDJYAU6H1pptqcA5fEAVelkZw1LP7si9bBrsF_u0")
var sheet = ss.getSheets()[0];
var lastrow = ss.getLastRow();
var d = new Date ();
var id ="0B1-7TPSHWZ1bMlNLTV9tTFJNb2c"; // cartella Raccolta DDT
var folder = DriveApp.getFolderById(id);
//Get information from form and set as variables
//var email = "pasquale.martucci#decathlon.com";
var email = e.values[1];
var mittente = e.values[2];
var destinatario = e.values[3];
var primaQnt = e.values[4];
var primaDescr = e.values[5];
var secondaQnt = e.values[6];
var secondaDescr = e.values[7];
var terzaQnt = e.values[8];
var terzaDescr = e.values[9];
var quartaQnt = e.values[10];
var quartaDescr = e.values[11];
var quintaQnt = e.values[12];
var quintaDescr = e.values[13];
var aspetto = e.values[14];
var colli = e.values[15];
var peso = e.values[16];
var vettore = e.values[17];
// Ricava indirizzi e città
var cell1 = sheet.getRange("S"+lastrow);
cell1.setFormula("=VLOOKUP(C"+lastrow+";Foglio2!A1:C35;2;FALSE)");
var indirMitt = cell1.getValue()
var cell2 = sheet.getRange("T"+lastrow);
cell2.setFormula("=VLOOKUP(C"+lastrow+";Foglio2!A1:C35;3;FALSE)");
var citMitt = cell2.getValue()
var cell3 = sheet.getRange("U"+lastrow);
cell3.setFormula("=VLOOKUP(D"+lastrow+";Foglio2!A1:C35;2;FALSE)");
var indirDest = cell3.getValue()
var cell4 = sheet.getRange("V"+lastrow);
cell4.setFormula("=VLOOKUP(D"+lastrow+";Foglio2!A1:C35;3;FALSE)");
var citDest = cell4.getValue()
//Ricava data
var day = sheet.getRange("W"+lastrow);
day.setFormula("=(DAY(A"+lastrow+"))");
var month = sheet.getRange("X"+lastrow);
month.setFormula("=(MONTH(A"+lastrow+"))");
var year = sheet.getRange("Y"+lastrow);
year.setFormula("=(YEAR(A"+lastrow+"))");
var day1 = sheet.getRange("W"+lastrow).getValue();
var month1 = sheet.getRange("X"+lastrow).getValue();
var year1 = sheet.getRange("Y"+lastrow).getValue();
var data = day1+"/"+month1+"/"+year1;
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' N° '+lastrow+' ' +mittente , folder)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyMittente', mittente);
copyBody.replaceText('keyDestinatario', destinatario);
copyBody.replaceText('keyQNT1', primaQnt);
copyBody.replaceText('keyDescrizione1', primaDescr);
copyBody.replaceText('keyQNT2', secondaQnt);
copyBody.replaceText('keyDescrizione2',secondaDescr);
copyBody.replaceText('keyQNT3', terzaQnt);
copyBody.replaceText('keyDescrizione3', terzaDescr);
copyBody.replaceText('keyQNT4', quartaQnt);
copyBody.replaceText('keyDescrizione4', quartaDescr);
copyBody.replaceText('keyQNT5', quintaQnt);
copyBody.replaceText('keyDescrizione5', quintaDescr);
copyBody.replaceText('keyAspetto', aspetto);
copyBody.replaceText('keyKg', peso);
copyBody.replaceText('keyColli', colli);
copyBody.replaceText('keyVettore', vettore);
copyBody.replaceText('keyIndirMitt', indirMitt);
copyBody.replaceText('keyCitMitt', citMitt);
copyBody.replaceText('keyIndirDest', indirDest);
copyBody.replaceText('keyCitDest', citDest);
copyBody.replaceText('keyNum', lastrow);
copyBody.replaceText('keyData', data);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "DDT";
var body = "In allegato il DDT generato tramite il portale SimplyCar.";
GmailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
// DriveApp.getFileById(copyId).setTrashed(true);
}

How to get Rates from UPS Rate API?

I am using nopcommerce 3.5. I have added plugin of UPS of TransitInTime and Rate API. I want to get rates by calling UPS Rate API. I want all Rates in dropdown on page load.
So for the first I am using test application using webservices of RateWebReference and in which I get only one Rate but I want Rates for all shipping option.
Here is my code of RateWSClient.cs
RateService rate = new RateService();
RateRequest rateRequest = new RateRequest();
UPSSecurity upss = new UPSSecurity();
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = "CC....";
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = "gi..";
upssUsrNameToken.Password = "Ch..";
upss.UsernameToken = upssUsrNameToken;
rate.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "Rate" };
request.RequestOption = requestOption;
rateRequest.Request = request;
ShipmentType shipment = new ShipmentType();
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = "A65V88";
RateWSSample.RateWebReference1.AddressType shipperAddress = new RateWSSample.RateWebReference1.AddressType();
String[] addressLine = { "", "", "" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "";
shipperAddress.PostalCode = "30076";
shipperAddress.StateProvinceCode = "GA";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
RateWSSample.RateWebReference1.AddressType shipFromAddress = new RateWSSample.RateWebReference1.AddressType();
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "";
shipFromAddress.PostalCode = "30076";
shipFromAddress.StateProvinceCode = "GA";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "", "", "" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "";
shipToAddress.PostalCode = "92262";
shipToAddress.StateProvinceCode = "";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipment.ShipTo = shipTo;
CodeDescriptionType service = new CodeDescriptionType();
//Below code uses dummy date for reference. Please udpate as required.
service.Code = "02";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "125";
CodeDescriptionType uom = new CodeDescriptionType();
uom.Code = "LBS";
uom.Description = "pounds";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
CodeDescriptionType packType = new CodeDescriptionType();
packType.Code = "02";
package.PackagingType = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
//Shipping Rate Chart
// ShipmentRatingOptionsType SRO = new ShipmentRatingOptionsType();
//SRO.RateChartIndicator = "";
//shipment.ShipmentRatingOptions= SRO;
//rateRequest.Shipment = shipment;
ShipmentRatingOptionsType SRO = new ShipmentRatingOptionsType();
SRO.NegotiatedRatesIndicator = "";
shipment.ShipmentRatingOptions = SRO;
rateRequest.Shipment = shipment;
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
Console.WriteLine(rateRequest);
RateResponse rateResponse = rate.ProcessRate(rateRequest);
Console.WriteLine("The transaction was a " + rateResponse.Response.ResponseStatus.Description);
Console.WriteLine("Total Shipment Charges " + rateResponse.RatedShipment[0].TotalCharges.MonetaryValue + rateResponse.RatedShipment[0].TotalCharges.CurrencyCode);
Console.ReadKey();
I have resolved this questions. So If you face this kind of problem don't forget to use
String[] requestOption = { "Shop" };
in place of
String[] requestOption = { "Rate" };
Then you will get rates for all shipping options.

To create an spreadsheet document in OPEN XML and and add an TABLE to it

I am trying to create an spread sheet by open xml with an table. But while opening the created excel file always it returns the error "Excel found unreadable content in test1.xlsx, do u want to recover. Why this error always happens? When the excel is created without table, i didnt get any error. Please find the below sample code which i used to create.
using (SpreadsheetDocument spreadsheetdocument = SpreadsheetDocument.Create(#"c://test.xlsx", SpreadsheetDocumentType.Workbook))
{
// add a workbookpart to the document.
WorkbookPart workbookpart = spreadsheetdocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// add a worksheetpart to the workbookpart.
WorksheetPart worksheetpart = workbookpart.AddNewPart<WorksheetPart>();
worksheetpart.Worksheet = new Worksheet(new SheetData());
// add sheets to the workbook.
Sheets sheets = spreadsheetdocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetdocument.WorkbookPart.
GetIdOfPart(worksheetpart),
SheetId = 1,
Name = "mysheet"
};
sheets.Append(sheet);
TableDefinitionPart tableDefinitionPart = worksheetpart.AddNewPart<TableDefinitionPart>("rId1");
GenerateTablePartContent(ref tableDefinitionPart);
TableParts tableParts1 = new TableParts() { Count = (UInt32Value)2U };
TablePart tablePart1 = new TablePart() { Id = "rId1" };
tableParts1.Append(tablePart1);
worksheetpart.Worksheet.Append(tableParts1);
spreadsheetdocument.Close();
}
//Added spaces to get the code in one block
private void GenerateTablePartContent(TableDefinitionPart part)
{
Table table1 = new Table() { Id = (UInt32Value)1U, Name = "Table1", DisplayName = "Table1", Reference = "A1:C3", TotalsRowShown = false };
AutoFilter autoFilter1 = new AutoFilter() { Reference = "A1:C3" };
TableColumns tableColumns1 = new TableColumns() { Count = (UInt32Value)3U };
TableColumn tableColumn1 = new TableColumn() { Id = (UInt32Value)1U, Name = "Column1" };
TableColumn tableColumn2 = new TableColumn() { Id = (UInt32Value)2U, Name = "Column2" };
TableColumn tableColumn3 = new TableColumn() { Id = (UInt32Value)3U, Name = "Column3" };
tableColumns1.Append(tableColumn1);
tableColumns1.Append(tableColumn2);
tableColumns1.Append(tableColumn3);
TableStyleInfo tableStyleInfo1 = new TableStyleInfo() { Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false };
table1.Append(autoFilter1);
table1.Append(tableColumns1);
table1.Append(tableStyleInfo1);
part.Table = table1;
}
use Open XML SDK Productivity Tool for it. Create an excel file using normal way and put same data there as well and compare that file with the file you are creating with your code. You will see the changes there. I am also facing same issue and I am trying to fix the changes using that tool. Lets see....
and If you have solved the issue please guide me how to do it.

Merging and grouping libraries code problem

I'm writing C# code to merge multiple libraries within a site collection and applying grouping on them. But grouping doesn't include documents from other sites regardless all share same meta data. Below, Blue box docs are from one site and green box docs are from other site and they don't group together.
Here are my code ,
DataTable dt = new DataTable();
DataRow dr;
DataColumn dc;
SPSite curSite = SPContext.Current.Site;
SPWebCollection subSites = curSite.AllWebs;
dc = new DataColumn("Title", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("ReferenceNo", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Domain", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Created", Type.GetType("System.DateTime"));
dt.Columns.Add(dc);
for (int i = 0; i < subSites.Count; i++)
{
SPListCollection lists = subSites[i].Lists;
foreach (SPList list in lists)
{
if (list.Title == "Published Documents")
{
SPQuery myquery = new SPQuery();
//myquery.Query = "<GroupBy><FieldRef Name='Domain' /></GroupBy><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";
myquery.Query = "<GroupBy><FieldRef Name='Domain' /></GroupBy>";
SPListItemCollection items = list.GetItems(myquery);
foreach (SPListItem item in items)
{
if (item != null)
{
dr = dt.NewRow();
dr["Title"] = item["Title"];
dr["ReferenceNo"] = item["ReferenceNo"];
dr["Domain"] = item["Domain"];
dr["Created"] = item["Created"];
dt.Rows.Add(dr);
}
}
}
}
}
//dt.DefaultView.Sort = "Created DESC";
spGridView.AllowGrouping = true;
spGridView.AllowGroupCollapse = true;
spGridView.GroupField = "Domain";
spGridView.DataSource = dt;
spGridView.DataBind();
Updates:: , Sorting Data Table with Domain fixed the issue..
**dt.DefaultView.Sort = "Domain";**
Rishi's answer:
Sorting Data Table with Domain fixed the issue..
dt.DefaultView.Sort = "Domain";
naveed's comment:
Perfect it worked for me. all goes well just we need to have
dt.DefaultView.Sort = "Your Sorting Attribute";