Adicionando obejeto dataset (database tipada)

This commit is contained in:
Adriano Serighelli 2023-05-23 11:05:52 -03:00
parent ff9603c84d
commit f11bc9f194
9 changed files with 7701 additions and 304 deletions

6661
Download Faturas/DataSet1.Designer.cs generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!--<autogenerated>
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
</autogenerated>-->
<DataSetUISetting Version="1.00" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TableUISettings />
</DataSetUISetting>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@


View File

@ -17,4 +17,31 @@
<PackageReference Include="System.Text.Json" Version="7.0.2" /> <PackageReference Include="System.Text.Json" Version="7.0.2" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Update="DataSet1.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>DataSet1.xsd</DependentUpon>
</Compile>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="DataSet1.xsd">
<Generator>MSDataSetGenerator</Generator>
<LastGenOutput>DataSet1.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -16,7 +16,7 @@
* *
*/ */
private string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ"; private const string Token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
private JsonElement faturaParsed; private JsonElement faturaParsed;
@ -24,7 +24,7 @@
{ {
// Utilizado para gerar novo token // Utilizado para gerar novo token
// this.token = Req_token(httpClient).ToString(); // this.token = Req_token(httpClient).ToString();
HttpResponseMessage fatura_response = this.GetStatus(httpClient, this.token, id); HttpResponseMessage fatura_response = this.GetStatus(httpClient, Token, id);
if (fatura_response.IsSuccessStatusCode) if (fatura_response.IsSuccessStatusCode)
{ {
this.faturaParsed = JsonDocument.Parse(fatura_response.Content.ReadAsStringAsync().Result).RootElement; this.faturaParsed = JsonDocument.Parse(fatura_response.Content.ReadAsStringAsync().Result).RootElement;
@ -66,7 +66,7 @@
cmd.CommandText = selectSQL; cmd.CommandText = selectSQL;
var unidades = (int)cmd.ExecuteScalar(); int? unidades = (int?)cmd.ExecuteScalar();
if (unidades == 1) if (unidades == 1)
{ {

View File

@ -43,14 +43,10 @@
// Verifica se a fatura foi processada e atualiza os valores para o banco de dados // Verifica se a fatura foi processada e atualiza os valores para o banco de dados
Fatura fatura = new Fatura(fatura_ID, fatura_arquivo, httpClient); Fatura fatura = new Fatura(fatura_ID, fatura_arquivo, httpClient);
// bool agrupada = fatura.Agrupada;
// string status = fatura.Status;
if (fatura.Status == "SUCCESS" & !fatura.Agrupada) if (fatura.Status == "SUCCESS" & !fatura.Agrupada)
{ {
// (string? status, string? pasta_middle, string? uc, int mes) fatura_processamento = processar_fatura(result, fatura_ID, fatura_arquivo);
// fatura_status = fatura_processamento.status;
fatura.Processar(cmd); fatura.Processar(cmd);
sw.WriteLine(fatura_ID + "," + fatura_status + "," + fatura_arquivo); sw.WriteLine(fatura_ID + "," + fatura.Status + "," + fatura_arquivo);
// mover_fatura(fatura_processamento, fatura_arquivo); // mover_fatura(fatura_processamento, fatura_arquivo);
} }
@ -63,13 +59,14 @@
if (faturaIndividual.Status == "SUCCESS") if (faturaIndividual.Status == "SUCCESS")
{ {
faturaIndividual.Processar(cmd); faturaIndividual.Processar(cmd);
sw.WriteLine(individual_ID.ToString() + "," + fatura_status + "," + fatura_arquivo);
sw.WriteLine(individual_ID.ToString() + "," + faturaIndividual.Status + "," + fatura_arquivo);
faturaIndividual.Mover();
// mover fatura // mover fatura
} }
else else
{ {
sw.WriteLine(individual_ID.ToString() + "," + result_individual.GetProperty("status").GetString() + "," + fatura_arquivo); sw.WriteLine(individual_ID.ToString() + "," + faturaIndividual.Status + "," + fatura_arquivo);
// mover fatura // mover fatura
} }
@ -77,7 +74,7 @@
} }
else else
{ {
sw.WriteLine(fatura_ID + "," + result.GetProperty("status").GetString() + "," + fatura_arquivo); sw.WriteLine(fatura_ID + "," + fatura.Status + "," + fatura_arquivo);
// mover fatura // mover fatura
} }
@ -93,298 +90,5 @@
sw.Close(); sw.Close();
File.Move(LogFaturas2, LogFaturas, true); File.Move(LogFaturas2, LogFaturas, true);
} }
/*public static (string? status, string? pasta_middle, string? uc, int mes) processar_fatura(JsonElement result, string fatura_ID, string fatura_arquivo)
{
// Variavel para armazenar os dados a serem lancados para a TUSD no BD
recordSet dadosTusd = new ();
// Resultado da fatura processada
Rootobject parsedResult = JsonSerializer.Deserialize<Rootobject>(result.GetProperty("result"));
dadosTusd.Mes = int.Parse(parsedResult.dates.reading.periodUntil.AddDays(-15).ToString("yMM"));
string uc = new Regex("^0+").Replace(parsedResult.locationNumber, string.Empty);
// Vinculo da fatura com os dados cadastrais
string selectSQL = $"SELECT COUNT (Cod_Smart_unidade) FROM Dados_cadastrais WHERE Codigo_Instalacao = '{uc}'";
cmd.CommandText = selectSQL;
var unidades = (int)cmd.ExecuteScalar();
if (unidades == 1)
{
selectSQL = $"SELECT Cod_Smart_unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP, Caminho_NFs FROM Dados_cadastrais WHERE Codigo_Instalacao = '{uc}'";
}
else
{
selectSQL = $"SELECT Cod_Smart_unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP, Caminho_NFs FROM Dados_cadastrais WHERE (CNPJ_CPF LIKE '{parsedResult.customer.cnpj?.Substring(0, 8) ?? "NAN"}%' AND Codigo_Instalacao = '{uc}') OR (Razao_Social LIKE '{parsedResult.customer.name}' AND Codigo_Instalacao = '{uc}')";
}
cmd.CommandText = selectSQL;
OleDbDataReader reader = cmd.ExecuteReader();
string pasta_faturas = "";
while (reader.Read())
{
// Dados cadastrais
dadosTusd.Cod_Smart_unidade = long.Parse(reader["Cod_Smart_unidade"].ToString());
dadosTusd.Perfil_CliqCCEE = reader["PerfilCCEE"].ToString();
dadosTusd.Submercado = reader["Submercado"].ToString();
dadosTusd.Ambiente = reader["Status_unidade"].ToString();
dadosTusd.Grupo = reader["Grupo"].ToString();
dadosTusd.Distribuidora = reader["Distribuidora"].ToString();
dadosTusd.ICMS = float.Parse(reader["ICMS_TUSD"].ToString());
dadosTusd.Dem_Cont_P = float.Parse(reader["Demanda_P"].ToString());
dadosTusd.Dem_Cont_FP = float.Parse(reader["Demanda_FP"].ToString());
pasta_faturas = reader["Caminho_NFs"].ToString();
}
reader.Close();
// Verifica se a fatura ja foi lançada
selectSQL = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = {long.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString())}";
cmd.CommandText = selectSQL;
reader = cmd.ExecuteReader();
bool tusdLanc = reader.HasRows;
reader.Close();
if (dadosTusd.Cod_Smart_unidade == 0)
{
return ("UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD", pasta_faturas, uc, dadosTusd.Mes);
}
else if (tusdLanc)
{
return ("FATURA DUPLICADA NO BD", pasta_faturas, uc, dadosTusd.Mes);
}
else
{
//PIS e Cofins
string pisSQL = $"SELECT Distribuidoras_PIS.PIS, Distribuidoras_PIS.COFINS FROM Distribuidoras_geral INNER JOIN Distribuidoras_PIS ON Distribuidoras_geral.ID_dist = Distribuidoras_PIS.ID_dist WHERE Distribuidoras_PIS.Mes='{dadosTusd.Mes}' AND Distribuidoras_geral.Distribuidora='{dadosTusd.Distribuidora}'";
cmd.CommandText = pisSQL;
reader = cmd.ExecuteReader();
while (reader.Read())
{
//PIS e Cofins
dadosTusd.PIS = float.Parse(reader["PIS"].ToString());
dadosTusd.COFINS = float.Parse(reader["COFINS"].ToString());
}
reader.Close();
//Dados da fatura processada
dadosTusd.Cod_TUSD = long.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString());
dadosTusd.Perfil = parsedResult.tariffModality == "blue" ? "AZUL" : "VERDE";
dadosTusd.Valor = parsedResult.totalCharges;
dadosTusd.Inicio_Leitura = parsedResult.dates.reading.periodFrom;
dadosTusd.Fim_leitura = parsedResult.dates.reading.periodUntil;
dadosTusd.Hora_TUSD = DateTime.Now;
dadosTusd.Dem_Reativa_kvar = 0;
dadosTusd.Multa = 0;
dadosTusd.Credito = 0;
dadosTusd.Bandeira_RS_MWh = 0;
dadosTusd.FIC_DIC = 0;
dadosTusd.Enc_conexao = 0;
dadosTusd.Liminar_ICMS = 0;
dadosTusd.Outros = 0;
dadosTusd.Cred_livre = 0;
dadosTusd.Tempo_TUSD = 0;
dadosTusd.Lanc_aut = true;
dadosTusd.Rev_atual = true;
dadosTusd.Revisao = 0;
//Loop entre os dados faturados na fatura
int j = 0;
foreach (Item item in parsedResult.items)
{
switch (item.type, item.period)
{
//Energia Ponta
case ("energy", "peak"):
dadosTusd.Consumo_P = item.billed / 1000;
break;
//Energia Fora de Ponta
case ("energy", "off-peak"):
dadosTusd.Consumo_FP = item.billed / 1000;
break;
//Demanda Ponta
case ("demand", "peak"):
dadosTusd.Dem_Cont_P = item.contract == 0 ? dadosTusd.Dem_Cont_P : item.contract;
break;
//Demanda Fora de Ponta
case ("demand", "off-peak"):
dadosTusd.Dem_Cont_FP = item.contract == 0 ? dadosTusd.Dem_Cont_FP : item.contract;
break;
//Ilum. publica
case ("publicLighting", _):
dadosTusd.Ilum_Publica = item.charge;
break;
//Energia Reativa
case ("excessReactiveEnergy", _):
dadosTusd.En_Reativa_Mvarh = item.billed / 1000 + dadosTusd.En_Reativa_Mvarh;
break;
//Demanda Reativa
case ("excessReactiveDemand", _):
dadosTusd.Dem_Reativa_kvar = item.billed;
break;
//Bandeira Tarifaria
case ("flagSurcharge", _):
dadosTusd.Bandeira_RS_MWh = item.charge;
break;
//Items não classificados
case ("other", _):
j++;
//Exclui os items lançados anteriormente para a fatura
if (j == 1)
{
string deleteOthers = $"DELETE FROM Dados_TUSD_aux WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}";
cmd.CommandText = deleteOthers;
cmd.ExecuteNonQuery();
}
//Insere os novos items
string insertOthers = "INSERT INTO Dados_TUSD_aux (Cod_TUSD,Id,Nome,Valor,Cod_lanc) VALUES (" + dadosTusd.Cod_TUSD + "," + j + ",'" + item.name + "'," + item.charge.ToString(new CultureInfo("en-US")) + "," + 0 + ")";
cmd.CommandText = insertOthers;
cmd.ExecuteNonQuery();
break;
}
}
//Busca a demanda registrada nos itens medidos
foreach (Measureditem measuredItem in parsedResult.measuredItems)
{
switch (measuredItem.type, measuredItem.period)
{
case ("demand", "peak"):
dadosTusd.Dem_Reg_P = measuredItem.measured;
break;
case ("demand", "off-peak"):
dadosTusd.Dem_Reg_FP = measuredItem.measured;
break;
}
}
var dados = dadosTusd.GetType().GetProperties();
StringBuilder fields = new StringBuilder();
StringBuilder values = new StringBuilder();
//Verifica se já existe a fatura lançada | atualizar fatura ou nova fatura
string selectTUSD = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}";
cmd.CommandText = selectTUSD.ToString();
reader = cmd.ExecuteReader();
if (reader.Read())
{
//Cria o comando para atualização da fatura
reader.Close();
StringBuilder updateSQL = new StringBuilder("UPDATE Dados_TUSD SET ");
//Loop por todos os dados ja obtidos
for (var i = 0; i < dados.Count(); i++)
{
//Adiciona o nome do campo
string field = dados[i].Name + "=";
//Valor para o campo selecionado
var value = dados[i].GetValue(dadosTusd) ?? "";
//Adiciona '(aspas) para textos e datas
if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime")
{
value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? "") + "'";
}
//Substitui ,(virgula) por .(ponto)
else if (dados[i].PropertyType.Name == "Single")
{
float valueFloat = (float)value;
value = valueFloat.ToString(new CultureInfo("en-US"));
}
if (i > 0)
{
updateSQL.Append(",");
}
updateSQL.Append(field + value);
}
updateSQL.Append($" WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}");
cmd.CommandText = updateSQL.ToString();
cmd.ExecuteNonQuery();
}
else
{
//Cria o comando para lançar da fatura
reader.Close();
StringBuilder insertSQL = new StringBuilder("INSERT INTO Dados_TUSD (");
//Loop pelo nome dos campos
for (var i = 0; i < dados.Count(); i++)
{
//Adiciona o nome do campo
string field = dados[i].Name;
//Valor para o campo selecionado
var value = dados[i].GetValue(dadosTusd) ?? "";
//Adiciona '(aspas) para textos e datas
if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime")
{
value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? "") + "'";
}
//Substitui ,(virgula) por .(ponto)
else if (dados[i].PropertyType.Name == "Single")
{
float valueFloat = (float)value;
value = valueFloat.ToString(new CultureInfo("en-US"));
}
if (i > 0)
{
fields.Append(",");
values.Append(",");
}
fields.Append(field);
values.Append(value);
}
insertSQL.Append(fields)
.Append(") VALUES (")
.Append(values)
.Append(")");
cmd.CommandText = insertSQL.ToString();
cmd.ExecuteNonQuery();
}
return ("FATURA INCLUIDA NO BD", pasta_faturas, uc, dadosTusd.Mes);
}
}*/
/*public static void mover_fatura((string? status, string? pasta_middle, string? uc, int mes) fatura, string fatura_arquivo, bool multiple = false)
{
switch (fatura.status)
{
case "":
break;
case "a":
break;
case "b":
break;
}
}
*/
} }
} }

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Download_Faturas.Properties {
using System;
/// <summary>
/// Uma classe de recurso de tipo de alta segurança, para pesquisar cadeias de caracteres localizadas etc.
/// </summary>
// Essa classe foi gerada automaticamente pela classe StronglyTypedResourceBuilder
// através de uma ferramenta como ResGen ou Visual Studio.
// Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente
// com a opção /str, ou recrie o projeto do VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Retorna a instância de ResourceManager armazenada em cache usada por essa classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Download_Faturas.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Substitui a propriedade CurrentUICulture do thread atual para todas as
/// pesquisas de recursos que usam essa classe de recurso de tipo de alta segurança.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>