Why are my margins changing on second page using itextsharp? - itext

I am using itextsharp to create pdfs. However, for some reason that I can't fathom, when the text goes onto the second page, it jumps down a line. I'm not adding a Chunk.NEWLINE anywhere, so I can only assume the document margin changes. This change only happens from page 1-2; it then remains constant for the rest of the document.
I noticed it when I created a method to add a header to the page, which overwrites OnEndPage; nevertheless, the effect happens when I don't call the method, and don't change OnEndPage at all, or the margins. Can anyone tell me why this is happening?
Here is the code I use to create my pdf:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using it = iTextSharp.text;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using Helper;
namespace Andrew
{
public class AndrewFunctions
{
public void createPDF()
{
//Create new document
Document doc = new Document(PageSize.A4);
//Create instance= of pdfwriter named test to write to file
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(#"C:\Users\Gabriela\Desktop\test.pdf", FileMode.Create));
try
{
//Add primary info to pdf and open for editing
doc.AddTitle("My first pdf");
doc.AddCreator("Andrew Birch");
//Set font and color
it.Font myfont = FontFactory.GetFont("Garamond");
myfont.SetColor(51, 51, 255);
doc.Open();
//Add filler content to pdf
for (int i = 0; i < 1200; i++)
{
doc.Add(new Phrase("This is filler text", myfont));
}
//Create header table
PdfPTable testTable = new PdfPTable(3);
testTable.WidthPercentage = 100f;
float[] widths = { 1f, 3f, 1f };
testTable.SetWidths(widths);
//Header table images
string path = "C:\\Users\\Gabriela\\Desktop\\descarga.png";
it.Image logo = doc.ImportarImagen(path, 24f);
path = "C:\\Users\\Gabriela\\Desktop\\descarga2.png";
it.Image logo2 = doc.ImportarImagen(path, 24f, AlineacionCelda.CentradoVCentradoH);
//Fill header table
doc.CrearCeldaImagen(logo, testTable, false, it.Color.BLUE, AlineacionCelda.CentradoVCentradoH, rowspan: 4);
doc.CrearCelda("TEST TABLE HEADER", testTable, font, it.Color.BLUE, AlineacionCelda.Centro, BordeCelda.SinBorde);
doc.CrearCeldaImagen(logo2, testTable, false, it.Color.BLUE, AlineacionCelda.CentradoVCentradoH, rowspan: 4);
doc.CrearCelda("HEADER LINE TWO WITH A WICKED SUBTITLE", testTable, font, it.Color.BLUE, AlineacionCelda.Centro, BordeCelda.SinBorde);
doc.CrearCelda("HEADER LINE THREE", testTable, font, it.Color.BLUE, AlineacionCelda.Centro, BordeCelda.SinBorde);
doc.CrearCelda("YOU GUESSED IT, HEADER LINE 4", testTable, font, it.Color.BLUE, AlineacionCelda.Centro, BordeCelda.SinBorde);
//Add heading before opening doc
doc.AgregarCabezado(testTable, writer, doc);
}
catch (it.DocumentException dex)
{
Console.WriteLine(dex.Message);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
finally
{
//Close doc and writing stream
doc.Close();
writer.Close();
}
}
The difference is more easily appreciated with the header, some screenshots to show what I mean:
Without Header, page 1
Without Header, page 2
With Header, page 1: i.stack.imgur.com/m8rmm.png
With Header, page 2: i.stack.imgur.com/VV8a7.png
The namespace Helper:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using it = iTextSharp.text;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Web;
namespace Helper
{
//Alignment values
public enum AlineacionCelda : byte
{
Izquierda = 1,
Centro,
Derecha,
AbajoIzquierda,
CentradoVCentradoH,
Justificado
}
//Border values
public enum BordeCelda : byte
{
SinBorde,
Arriba,
Abajo,
ArribaAbajo,
Izquierda,
IzquierdoArriba,
IzquierdoAbajo,
IzquierdoArribaAbajo,
Derecha,
DerechaArriba,
DerechaAbajo,
DerechaArribaAbajo,
DerechaIzquierda,
DerechaIzquierdaArriba,
DerechaIzquierdaAbajo,
Todos
}
public class Pdf : it.Document
{
//Default variables
public static it.Font fuenteDefaultStatic = FontFactory.GetFont("Arial", 11, it.Font.NORMAL, it.Color.BLACK);
public it.Font fuenteDefault = FontFactory.GetFont("Arial", 11, it.Font.NORMAL, it.Color.BLACK);
public it.Font fuentePartidaDefault = FontFactory.GetFont("Arial", 9, it.Font.NORMAL, it.Color.BLACK);
public it.Font fuentePartidaNegritaDefault = FontFactory.GetFont("Arial", 9, it.Font.BOLD, it.Color.BLACK);
public it.Font fuenteNegritaDefault = FontFactory.GetFont("Arial", 11, it.Font.BOLD, it.Color.BLACK);
public it.Color fondoDefault = iTextSharp.text.Color.WHITE;
public Pdf() : base() { }
public Pdf(it.Rectangle pageSize): base(pageSize) {}
public Pdf(it.Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom) : base(pageSize, marginLeft, marginRight, marginTop, marginBottom) { }
//Create a cell in the table specified with the attributes specified: use default values if any are omitted.
public void CrearCelda(string valor, PdfPTable tabla, iTextSharp.text.Font fuente = default(it.Font), it.Color fondo = default(it.Color), AlineacionCelda alineacion = AlineacionCelda.Izquierda, BordeCelda borde = BordeCelda.Todos,
int colspan = 1, int rowspan = 1)
{
try
{
if (fuente == default(it.Font))
{
fuente = fuenteDefault;
}
PdfPCell celda = new PdfPCell(new Phrase(valor, fuente));
if (fondo == default(it.Color))
{
fondo = fondoDefault;
}
celda.BackgroundColor = fondo;
switch (borde) //Check and set border accordingly
{
case BordeCelda.SinBorde: celda.Border = PdfPCell.NO_BORDER; break;
case BordeCelda.Arriba: celda.Border = PdfPCell.TOP_BORDER; break;
case BordeCelda.Abajo: celda.Border = PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.ArribaAbajo: celda.Border = PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Izquierda: celda.Border = PdfPCell.LEFT_BORDER; break;
case BordeCelda.IzquierdoArriba: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.IzquierdoAbajo: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.IzquierdoArribaAbajo: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Derecha: celda.Border = PdfPCell.RIGHT_BORDER; break;
case BordeCelda.DerechaArriba: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.DerechaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.DerechaArribaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.DerechaIzquierda: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER; break;
case BordeCelda.DerechaIzquierdaArriba: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.DerechaIzquierdaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Todos: celda.Border = PdfPCell.BOX; break;
}
if (colspan != 1)
{
celda.Colspan = colspan;
}
else
{
celda.Colspan = 1;
}
if (rowspan != 1)
{
celda.Rowspan = rowspan;
}
else
{
celda.Rowspan = 1;
}
switch (alineacion) //Check and set alignment accordingly
{
case AlineacionCelda.Izquierda: celda.HorizontalAlignment = Element.ALIGN_LEFT; break;
case AlineacionCelda.Centro: celda.HorizontalAlignment = Element.ALIGN_CENTER; break;
case AlineacionCelda.Derecha: celda.HorizontalAlignment = Element.ALIGN_RIGHT; break;
case AlineacionCelda.AbajoIzquierda: celda.HorizontalAlignment = Element.ALIGN_LEFT; celda.VerticalAlignment = Element.ALIGN_BOTTOM; break;
case AlineacionCelda.CentradoVCentradoH: celda.HorizontalAlignment = Element.ALIGN_CENTER; celda.VerticalAlignment = Element.ALIGN_MIDDLE; break;
case AlineacionCelda.Justificado: celda.HorizontalAlignment = Element.ALIGN_JUSTIFIED; break;
}
tabla.AddCell(celda);
}
catch (Exception ex)
{
throw ex;
}
}
//Creates cell containing the image specified in the table specified
public void CrearCeldaImagen(it.Image imagen, PdfPTable tabla, bool autoFit = false, it.Color fondo = default(it.Color), AlineacionCelda alineacion = AlineacionCelda.Izquierda, BordeCelda borde = BordeCelda.SinBorde,
int colspan = 1, int rowspan = 1)
{
try
{
PdfPCell celda = new PdfPCell(imagen, autoFit);
if (fondo != default(it.Color))
{
celda.BackgroundColor = fondo;
}
switch (alineacion) //Checks and sets the alignment accordingly
{
case AlineacionCelda.Izquierda: celda.HorizontalAlignment = Element.ALIGN_LEFT; break;
case AlineacionCelda.Centro: celda.HorizontalAlignment = Element.ALIGN_CENTER; break;
case AlineacionCelda.Derecha: celda.HorizontalAlignment = Element.ALIGN_RIGHT; break;
case AlineacionCelda.AbajoIzquierda: celda.HorizontalAlignment = Element.ALIGN_LEFT; celda.VerticalAlignment = Element.ALIGN_BOTTOM; break;
case AlineacionCelda.CentradoVCentradoH: celda.HorizontalAlignment = Element.ALIGN_CENTER; celda.VerticalAlignment = Element.ALIGN_MIDDLE; break;
default: celda.HorizontalAlignment = Element.ALIGN_LEFT; break;
}
switch (borde) //Checks and sets the border accordingly
{
case BordeCelda.SinBorde: celda.Border = PdfPCell.NO_BORDER; break;
case BordeCelda.Arriba: celda.Border = PdfPCell.TOP_BORDER; break;
case BordeCelda.Abajo: celda.Border = PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.ArribaAbajo: celda.Border = PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Izquierda: celda.Border = PdfPCell.LEFT_BORDER; break;
case BordeCelda.IzquierdoArriba: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.IzquierdoAbajo: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.IzquierdoArribaAbajo: celda.Border = PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Derecha: celda.Border = PdfPCell.RIGHT_BORDER; break;
case BordeCelda.DerechaArriba: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.DerechaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.DerechaArribaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.TOP_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.DerechaIzquierda: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER; break;
case BordeCelda.DerechaIzquierdaArriba: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER | PdfPCell.TOP_BORDER; break;
case BordeCelda.DerechaIzquierdaAbajo: celda.Border = PdfPCell.RIGHT_BORDER | PdfPCell.LEFT_BORDER | PdfPCell.BOTTOM_BORDER; break;
case BordeCelda.Todos: celda.Border = PdfPCell.BOX; break;
default: celda.Border = PdfPCell.NO_BORDER; break;
}
if (colspan != 1)
celda.Colspan = colspan;
else
{
celda.Colspan = 1;
}
if (rowspan != 1)
celda.Rowspan = rowspan;
else
celda.Rowspan = 1;
tabla.AddCell(celda);
}
catch (Exception ex)
{
throw ex;
}
}
//Returns the image at the specified path, using the scale percentage, alignment, and border specified
public it.Image ImportarImagen(string rutaImagen, float escalaPorcentaje = 100f, AlineacionCelda alineacion = AlineacionCelda.Izquierda, BordeCelda borde = BordeCelda.SinBorde)
{
it.Image imagen = it.Image.GetInstance(rutaImagen);
imagen.ScalePercent(escalaPorcentaje);
switch (alineacion) //Check and set alignment
{
case AlineacionCelda.Izquierda: imagen.Alignment = it.Image.ALIGN_LEFT; break;
case AlineacionCelda.Centro: imagen.Alignment = it.Image.ALIGN_CENTER; break;
case AlineacionCelda.Derecha: imagen.Alignment = it.Image.ALIGN_RIGHT; break;
case AlineacionCelda.CentradoVCentradoH: imagen.Alignment = it.Image.ALIGN_CENTER | it.Image.ALIGN_MIDDLE; break;
default: imagen.Alignment = Element.ALIGN_LEFT; break;
}
switch (borde) //Check and set border
{
case BordeCelda.SinBorde: imagen.Border = it.Image.NO_BORDER; break;
case BordeCelda.Arriba: imagen.Border = it.Image.TOP_BORDER; break;
case BordeCelda.Abajo: imagen.Border = it.Image.BOTTOM_BORDER; break;
case BordeCelda.ArribaAbajo: imagen.Border = it.Image.TOP_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.Izquierda: imagen.Border = it.Image.LEFT_BORDER; break;
case BordeCelda.IzquierdoArriba: imagen.Border = it.Image.LEFT_BORDER | it.Image.TOP_BORDER; break;
case BordeCelda.IzquierdoAbajo: imagen.Border = it.Image.LEFT_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.IzquierdoArribaAbajo: imagen.Border = it.Image.LEFT_BORDER | it.Image.TOP_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.Derecha: imagen.Border = it.Image.RIGHT_BORDER; break;
case BordeCelda.DerechaArriba: imagen.Border = it.Image.RIGHT_BORDER | it.Image.TOP_BORDER; break;
case BordeCelda.DerechaAbajo: imagen.Border = it.Image.RIGHT_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.DerechaArribaAbajo: imagen.Border = it.Image.RIGHT_BORDER | it.Image.TOP_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.DerechaIzquierda: imagen.Border = it.Image.RIGHT_BORDER | it.Image.LEFT_BORDER; break;
case BordeCelda.DerechaIzquierdaArriba: imagen.Border = it.Image.RIGHT_BORDER | it.Image.LEFT_BORDER | it.Image.TOP_BORDER; break;
case BordeCelda.DerechaIzquierdaAbajo: imagen.Border = it.Image.RIGHT_BORDER | it.Image.LEFT_BORDER | it.Image.BOTTOM_BORDER; break;
case BordeCelda.Todos: imagen.Border = it.Image.BOX; break;
default: imagen.Border = it.Image.NO_BORDER; break;
}
if (imagen.Border != it.Image.NO_BORDER)
{
imagen.BorderWidth = 1f;
}
return imagen;
}
public void agregarCabezado(PdfPTable tabla, PdfWriter writer, Document document)
{
//Change margins to adapt to the Header
document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + tabla.TotalHeight + 50f, document.BottomMargin);
Cabezado cabezado = new Cabezado(tabla);
writer.PageEvent = cabezado;
}
public class Cabezado : PdfPageEventHelper
{
//Table used for the header
public PdfPTable tablaCabezado { get; set; }
public Cabezado(PdfPTable tabla)
{
this.tablaCabezado = tabla;
}
// Place the header on each page
public override void OnEndPage(PdfWriter writer, Document document)
{
try
{
base.OnEndPage(writer, document);
//To ensure WriteSelectedRows respects the Rowspan
ArrayList tmp = tablaCabezado.GetRows(0, tablaCabezado.Size);
tablaCabezado.Rows.Clear();
tablaCabezado.Rows.AddRange(tmp);
//Calculate the positioning of the header
float posicionY = document.PageSize.Height - tablaCabezado.TotalHeight;
tablaCabezado.WriteSelectedRows(0, -1, 34, posicionY, writer.DirectContent);
}
catch (DocumentException ex)
{
throw ex;
}
}
}
}
}

Related

ASP.NET Core MVC : GET details using view model not working

I am having a problem using a view model to view get the details of an item selected in the view. I am loading a result into my index view as follows
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.ConOrgSortParm = String.IsNullOrEmpty(sortOrder) ? "Client_desc" : "Client";
ViewBag.AssignedSortParm = String.IsNullOrEmpty(sortOrder) ? "Assigned_desc" : "Assigned";
ViewBag.ExpiresSortParm = String.IsNullOrEmpty(sortOrder) ? "Expires_desc" : "Expires";
ViewBag.LastActiveSortParm = String.IsNullOrEmpty(sortOrder) ? "LastActive_desc" : "LastActive";
ViewBag.IDSortParm = String.IsNullOrEmpty(sortOrder) ? "Id_desc" : "";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var results = (from node in _context.Nodes
join bnbridge in _context.BundleNodes on node.Id equals bnbridge.NodeId into NodeBundleIDGroup
from ax in NodeBundleIDGroup.DefaultIfEmpty()
join bundle in _context.Bundles on ax.BundleId equals bundle.Id into NodeBundleGroup
from bx in NodeBundleGroup.DefaultIfEmpty()
join agreement in _context.Agreements on bx.AgreementId equals agreement.Id into agGroup
from cx in agGroup.DefaultIfEmpty()
join org in _context.Organizations on cx.OrgId equals org.Id into oGroup
from ex in oGroup.DefaultIfEmpty()
join conorg in _context.Organizations on node.OrgId equals conorg.Id into tGroup
from fx in tGroup.DefaultIfEmpty()
select new NodeIndexViewModel
{
Id = node.Id,
Name = node.Name,
AssignedOrg = fx.ShortName,
ContractingOrg = ex.ShortName,
Expiry = bx.EndUtc,
LastActive = node.ActiveDate,
NodeType = bx.NodeTypeID
});
if (!String.IsNullOrEmpty(searchString))
{
results = results.Where(s => s.AssignedOrg.Contains(searchString)
|| s.Id.ToString().StartsWith(searchString));
}
switch (sortOrder)
{
case "Client_desc":
results = results.OrderByDescending(s => s.ContractingOrg);
break;
case "Client":
results = results.OrderBy(s => s.ContractingOrg);
break;
case "Assigned":
results = results.OrderBy(s => s.AssignedOrg);
break;
case "Assigned_desc":
results = results.OrderByDescending(s => s.AssignedOrg);
break;
case "Expires":
results = results.OrderBy(s => s.Expiry);
break;
case "Expires_desc":
results = results.OrderByDescending(s => s.Expiry);
break;
case "LastActive":
results = results.OrderBy(s => s.LastActive);
break;
case "LastActive_desc":
results = results.OrderByDescending(s => s.LastActive);
break;
case "Id_desc":
results = results.OrderByDescending(s => s.Id);
break;
default:
results = results.OrderBy(s => s.Id);
break;
};
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(await results.ToPagedListAsync(pageNumber, pageSize));
}
This is working as expected. The problem comes when I want to access the Details of one of the listed results.
I have tried the following in the controller:
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.NodeIndexViewModel == null)
{
return NotFound();
}
var nodeIndexViewModel = await _context.NodeIndexViewModel
.FirstOrDefaultAsync(m => m.Id == id);
if (nodeIndexViewModel == null)
{
return NotFound();
}
return View(nodeIndexViewModel);
}
I get an error
PostgresException: 42P01: relation "NodeIndexViewModel" does not exist
Can't answer the question because I don't know what the problem was but I rescaffolded the database and it's working now.

Amplify DataStore: How to know when sync is finished?

How can we know that DataStore has finished the sync?
When doing the first await DataStore.query(MyEntity) after the user logged in, DataStore is returning right away and not waiting for the data to be synced with the cloud.
I want to wait for the sync to be completed and put a loading when the data isn't synced yet.
make your model class observable so that it can check for data in realtime
Amplify.DataStore.observeQuery(MyEntity.classType).listen((event) {
if (event.isSynced) {//boolean value
print("Synced Successfully!");
// even you can get synced data here also
List< MyEntity> items = event.items;
} else {
//Show ProgressBar Here
print("Fetching Data From Cloud");
}
});
You can listen to events on the datastore channel with Amplify.Hub.listen.
details:
subscription = Amplify.Hub.listen([HubChannel.DataStore], (dynamic hubEvent) async {
switch (hubEvent.eventName) {
case 'networkStatus':
_amplifyIsUp.value = hubEvent.payload.active;
break;
case 'subscriptionsEstablished':
_amplifyMessage.value = 'Starting to sync from cloud...';
break;
case 'syncQueriesStarted':
_amplifyIsSyncing.value = true;
_amplifyMessage.value = 'Syncing...';
break;
case 'modelSynced':
ModelSyncedEvent mse = hubEvent.payload;
_amplifyMessage.value = '${mse.modelName} has been sync\'d from cloud...';
break;
case 'syncQueriesReady':
_amplifyMessage.value = 'Done!';
_amplifyIsSyncing.value = false;
///do your bits here
onSyncsReady.call();
break;
case 'ready':
_amplifyIsSyncing.value = false;
break;
case 'subscriptionDataProcessed':
SubscriptionDataProcessedEvent sdpe = hubEvent.payload;
_amplifyMessage.value = 'Syncing ${sdpe.element.model.classType.modelName()}...';
if (sdpe.element.model is DeviceStatus) {
DeviceStatus ds = sdpe.element.model as DeviceStatus;
if (ds.clientID == _clientService.client.id && ds.status == Status.REQUESTSTATUS) {
_statusService.performHeartbeat();
}
}
break;
case 'outboxMutationEnqueued':
_amplifyIsSyncing.value = true;
_amplifyHasDirt.value = true;
break;
case 'outboxMutationProcessed':
OutboxMutationEvent ome = hubEvent.payload;
_amplifyIsSyncing.value = false;
break;
case 'outboxStatus':
OutboxStatusEvent ose = hubEvent.payload;
if (ose.isEmpty) {
_amplifyIsSyncing.value = false;
_amplifyHasDirt.value = false;
} else {
_amplifyHasDirt.value = true;
}
break;
}
});
boop

STM32 cant send data with esp8266 thingspeak.what did I wrong?

I am working on a project about send PWM values and time values(with RTC) from stm32 to wifi module and bluetooth module at the same time.I wrote a code for esp8266 and esp8266 connected to my phone.But didnt send any value to bluetooth module or thingspeak.What did I wrong?(I cant use HAL Library for this project)
static void Clear_ESPBuffer(void)
{
uint16_t i;
for(i=0;i<ESP8266BUFFER_LENGHT;i++)
g_arrui8ESP8266Buf[i] = 0;
ESPWriteIndex=0;
}
//esp8266 configuration
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1, &USART_InitStruct);
//bluetooth modulu configuration
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_Init(USART3, &USART_InitStruct);
USART_Cmd(USART3, ENABLE); // USART3 aktif edilir.
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
}
static void ESP8266_Init(void)
{
static uint8_t ESPInitCase=0;
switch(ESPInitCase)
{
case 0:
// Standart AT Komutu gonderilir , Cevabi OK olmalidir.
USART_puts(USART1,"AT\r\n");
Delay(1000000L);
ESPInitCase = 1;
break;
case 1:
if (strstr(g_arrui8ESP8266Buf,"OK") != NULL)
{
Clear_ESPBuffer();
USART_puts(USART3,"Module Erisildi\n");
ESPInitCase = 2;
}
else
{
Clear_ESPBuffer();
USART_puts(USART3,"Not Founded");
ESPInitCase = 0;
}
break;
case 2:
USART_puts(USART1,"AT+CWMODE?\r\n");
Delay(1000000L);
ESPInitCase = 3;
break;
case 3:
// Gelen cevap mode 1 'mi
if (strstr(g_arrui8ESP8266Buf,"+CWMODE:1") != NULL)
{
Clear_ESPBuffer();
USART_puts(USART3,"Config okey\n");
ESPInitCase = 4;
}
else
{
.
USART_puts(USART1,"AT+CWMODE=1\r\n");
USART_puts(USART1,"AT+RST\r\n");
Delay(1000000L);
Clear_ESPBuffer();
USART_puts(USART3,"Changed Mode.\n");
ESPInitCase = 2;
}
break;
case 4:
USART_puts(USART1,"AT+CWJAP=\"Wifi\",\"Password\"\r\n");
Delay(2000000L);
ESPInitCase = 5;
break;
case 5:
if (strstr(g_arrui8ESP8266Buf,"OK") != NULL)
{
Clear_ESPBuffer();
USART_puts(USART3,"Wifi Connected\n");
ESPInitCase = 6;
}
else
{
Delay(1000000L);
USART_puts(USART3,"waiting for wifi\n");
Delay(5000000L);
say2++;
if(say2==3)
{
USART_puts(USART3,"Not Connected\n");
ESPInitCase=8;
say2=0;
}
}
break;
case 6:
// For ıp adress
USART_puts(USART1,"AT+CIFSR\r\n");
Delay(1000000L);
ESPInitCase = 7;
break;
case 7:
if (strstr(g_arrui8ESP8266Buf,"ERROR") == NULL)
{
USART_puts(USART3," IP = \n");
USART_puts(USART3,&g_arrui8ESP8266Buf[11]);
Clear_ESPBuffer();
ESPInitCase=8;
}
else
{
Delay(1000000L);
USART_puts(USART3,"Try again.\n");
Clear_ESPBuffer();
ESPInitCase=6;
}
break;
case 8:
USART_puts(USART1,"AT+CIPSTART=\"TCP\",\"IP\",80\r\n");
// 1 saniye gecikme koyuyoruz.
Delay(1000000L);
ESPInitCase = 9;
break;
case 9:
if (strstr(g_arrui8ESP8266Buf,"CONNECT") != NULL)
{
Clear_ESPBuffer();
USART_puts(USART3,"connected to website\n");
ESPInitCase = 10;
}
else
{
Delay(1000000L);
USART_puts(USART3,"waiting for Website connection\n");
Delay(50000000L);
say++;
if(say==3)
{
USART_puts(USART3," Website didnt work .\n");
ESPInitCase=8;
say=0;
}
}
break;
case 10:
Value=Read_ADC(); // adc okunuyor
sprintf(transmitdata, "GET /update?key=9KT9JQA1PJXPTFJJ&field2=%d\r\n",value);
length=strlen(transmitdata);
length=length+2;
sprintf(transmitconf,"AT+CIPSEND=%d\r\n",length);
USART_puts(USART1,transmitconf);
Delay(10000000L);
if (strstr(g_arrui8ESP8266Buf,">") != NULL)
{
Clear_ESPBuffer();
USART_puts(USART1,transmitdata);
USART_puts(USART3,"transmitted data\n");
Delay(2000000L);
ESPInitCase=10;
}
else
{
Delay(3000000L);
USART_puts(USART3,"data length not okey\n");
ESPInitCase=8;
USART_puts(USART3,"trying to connect website again\n");
say3++;
if(say3==3)
{
USART_puts(USART3,"didnt connect.\n check config\n");
ESPInitCase=0;
say3=0;
}
}
break;
}
}
void USART1_IRQHandler(void)
{
if( USART_GetITStatus(USART1, USART_IT_RXNE) )
{
uint8_t Received_Byte = USART1->DR;
USART2->DR = Received_Byte;
if(Received_Byte != 0)
{
g_arrui8ESP8266Buf[ESPWriteIndex] = Received_Byte;
ESPWriteIndex++;
}
}
}

How can I convert english numbers into another language numbers (I am using Bengali language) in Flutter?

I am getting english numbers (e.g. 123) as integer, now I want to show it in another language form (e.g. ১২৩).
I used a function and it also worked. But, it doesn't work in same stateful class more than once.
It worked for the first Text widget but not for the second one
Column(
children<Widget>:[
Text(
"${convertNumber(123)}"
),
Text(
"${convertNumber(5630)}"
)
]
)
String convertNumber(int eng){
String bengali = '';
for(int i = 0; i < eng.toString().length; i ++){
setState(() {
switch(eng.toString()[i]){
case '1':
bengali = bengali + '১';
break;
case '2':
bengali = bengali + '২';
break;
case '3':
bengali = bengali + '৩';
break;
case '4':
bengali = bengali + '৪';
break;
case '5':
bengali = bengali + '৫';
break;
case '6':
bengali = bengali + '৬';
break;
case '7':
bengali = bengali + '৭';
break;
case '8':
bengali = bengali + '৮';
break;
case '9':
bengali = bengali + '৯';
break;
default:
bengali = bengali + '0';
}
});
}
return bengali;
}
While I am using it for other numbers in the same stateful class, it doesn't work. And error was :
setState() or markNeedsBuild() called during build
This LowerHalf widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: LowerHalf
Do not call setState inside your convert function, just use your function to get a value.
Widgets rebuild after you call setState function. In your case, build calls setState that triggers build again.
Create new function and return string after converting it.
Below function is for converting number from English to Hindi or Gujarati based on users selected language for application.
translateMobileNumber(String mobileNumber) {
var mobileNumberTrim = mobileNumber.toString().trim();
var translatedNumber = '';
var currentLan = 'gu';
switch (Get.locale.toString().substring(0, 2)) {
case 'gu':
currentLan = 'gu';
break;
case 'hi':
currentLan = 'hi';
break;
case 'en':
currentLan = 'en';
break;
default:
currentLan = 'en';
break;
}
if (currentLan == 'en') {
return mobileNumberTrim;
}
for (int i = 0; i < mobileNumberTrim.length; i++) {
switch (mobileNumberTrim[i]) {
case '0':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૦' : '$translatedNumber૦';
break;
case '1':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૧' : '$translatedNumber१';
break;
case '2':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૨' : '$translatedNumber२';
break;
case '3':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૩' : '$translatedNumber३';
break;
case '4':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૪' : '$translatedNumber४';
break;
case '5':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૫' : '$translatedNumber५';
break;
case '6':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૬' : '$translatedNumber६';
break;
case '7':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૭' : '$translatedNumber७';
break;
case '8':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૮' : '$translatedNumber८';
break;
case '9':
translatedNumber =
currentLan == 'gu' ? '$translatedNumber૯' : '$translatedNumber९';
break;
}
}
return translatedNumber;
}

Child Grid View's OnRowCommand not fired in Nested Grid View criteria

i m working with nested grid view scenario. how ever i found that my Child grid view's OnRowCommand not fired inside Parent grid view. i surfing and found one solution like.
After implementing this i have no effect. still my child grid view OnRowCommand not fired
for more information i place my code:
protected void GV_ViewServices_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header && this.ViewState["SortExp"] != null)
{
System.Web.UI.WebControls.Image ImgSort = new System.Web.UI.WebControls.Image();
if (this.ViewState["SortOrder"].Equals("ASC"))
ImgSort.ImageUrl = "../images/down_arrow_1.gif";
else
ImgSort.ImageUrl = "~/images/up_arrow_1.gif";
switch (this.ViewState["SortExp"].ToString())
{
case "Service_name":
PlaceHolder placeholderServiceName = (PlaceHolder)e.Row.FindControl("placeholderServiceName");
placeholderServiceName.Controls.Add(ImgSort);
break;
case "IsActive":
PlaceHolder placeholderstatus = (PlaceHolder)e.Row.FindControl("placeholderstatus");
placeholderstatus.Controls.Add(ImgSort);
break;
case "Service_desc":
PlaceHolder placeholderdescription = (PlaceHolder)e.Row.FindControl("placeholderdescription");
placeholderdescription.Controls.Add(ImgSort);
break;
case "Created_date":
PlaceHolder placeholderdate = (PlaceHolder)e.Row.FindControl("placeholderdate");
placeholderdate.Controls.Add(ImgSort);
break;
}
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.GridView GV_ViewServiceFeature = (System.Web.UI.WebControls.GridView)e.Row.FindControl("GV_ViewServiceFeature");
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
GV_ViewServiceFeature.PageIndex = Convert.ToInt16(dtPageIndex.Rows[e.Row.RowIndex][0]);
}
FillFeatureGrid(int.Parse(GV_ViewServices.DataKeys[e.Row.RowIndex].Value.ToString()), GV_ViewServiceFeature);
System.Web.UI.WebControls.GridView GV_ViewServiceCharge = (System.Web.UI.WebControls.GridView)e.Row.FindControl("GV_ViewServiceCharge");
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
GV_ViewServiceCharge.PageIndex = Convert.ToInt16(dtPageIndex.Rows[e.Row.RowIndex][0]);
}
FillChargeGrid(int.Parse(GV_ViewServices.DataKeys[e.Row.RowIndex].Value.ToString()), GV_ViewServiceCharge);
}
}
protected void GV_ViewServiceFeature_RowCommand(object sender, GridViewCommandEventArgs e)
{
foreach(GridViewRow row in GV_ViewServices.Rows)
{
GridView gv=row.FindControl("GV_ViewServiceFeature") as GridView;
if (e.CommandName.Equals("AddNew") && Page.IsValid)
{
TextBox txtfeaturetext = (TextBox)gv.FooterRow.FindControl("txtfeaturetext");
int returnValue = DatabaseHelper.AddNewServiceFeature(int.Parse(service_id.Value.ToString()), txtfeaturetext.Text.Trim());
if (returnValue > 0)
{
this.FillFeatureGrid(int.Parse(GV_ViewServices.DataKeys[row.RowIndex].Value.ToString()),gv);
}
}
int intCurIndex = gv.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "first":
gv.PageIndex = 0;
break;
case "prev":
CurrentPage -= 1;
break;
case "next":
CurrentPage += 1;
break;
case "last":
gv.PageIndex = gv.PageCount;
break;
}
this.FillFeatureGrid(int.Parse(GV_ViewServices.DataKeys[row.RowIndex].Value.ToString()), gv);
}
}
please help me out this problem.
first off all we have to manually register command at Parent grid view row_created event.
protected void GV_ViewServices_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = e.Row.FindControl("GV_ViewServiceFeature") as GridView;
gv.RowCommand += new GridViewCommandEventHandler(GV_ViewServiceFeature_RowCommand);
GridView gv1 = e.Row.FindControl("GV_ViewServiceCharge") as GridView;
gv1.RowCommand += new GridViewCommandEventHandler(GV_ViewServiceCharge_RowCommand);
}
}
protected void GV_ViewServiceFeature_RowCommand(object sender, GridViewCommandEventArgs e)
{
System.Web.UI.WebControls.GridView gv = ((System.Web.UI.WebControls.GridView)sender);
GridViewRow gvRowParent = ((System.Web.UI.WebControls.GridView)sender).Parent.Parent.Parent.Parent as GridViewRow;
if (e.CommandName.Equals("AddNew"))
{
Page.Validate("AddNewFeature");
TextBox txtfeaturetext = (TextBox)gv.FooterRow.FindControl("txtfeaturetext");
int returnValue = DatabaseHelper.AddNewServiceFeature(int.Parse(GV_ViewServices.DataKeys[gvRowParent.RowIndex].Value.ToString()), txtfeaturetext.Text.Trim());
if (returnValue > 0)
{
this.FillFeatureGrid(int.Parse(GV_ViewServices.DataKeys[gvRowParent.RowIndex].Value.ToString()), gv);
}
}
int intCurIndex = gv.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "first":
gv.PageIndex = 0;
break;
case "prev":
CurrentPage -= 1;
break;
case "next":
CurrentPage += 1;
break;
case "last":
gv.PageIndex = gv.PageCount;
break;
}
this.FillFeatureGrid(int.Parse(GV_ViewServices.DataKeys[gvRowParent.RowIndex].Value.ToString()),gv);
}