Jump to content

Recommended Posts

Posted

Boas pessoal,

Tenho uma página asp.net feita em c# a correr num servidor numa aplicação IIS. Nesse site tenho uma pagina que faz refresh automático de 5 em 5 segundos. Passado um tempo (as vezes uns minutos outras umas horas) a página estoira e apresenta esta mensagem:

Server Error in '/' Application.

Operation is not valid due to the current state of the object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: Operation is not valid due to the current state of the object.]
   Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlConnector.cs:1587
   Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:973
   Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:962
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +15
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +275
   Account_Login.refresh_logistics_table() +460
   Account_Login.Page_Load(Object sender, EventArgs e) +116
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

e às vezes aparece esta:

Server Error in '/' Application.

An operation is already in progress.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: An operation is already in progress.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: An operation is already in progress.]
   Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlConnector.cs:1592
   Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:973
   Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:962
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +15
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +275
   Account_Login.refresh_logistics_table() +460
   Account_Login.Page_Load(Object sender, EventArgs e) +116
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

Basta fazer refresh na página e tudo volta ao normal.

Alguém me consegue ajudar neste assunto?

  • Replies 48
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted

Boas,

Já não programo em .NET à bastante tempo, mas se bem me lembro esse erro ocorria quando expirava ou o view state da pagina, a sessão de utlizador ou a conexão á base de dados(como disse o migueldesousa).

Mas sem certezas :).

Posted

JaimeASV, és capaz de ter razão. Tambem já não olho para asp.net há algum tempo e o primeiro erro é algo semelhante ao que me recordo de erros do viewstate.. mas o ultimo pedido no stack trace mostra que é no acesso á bd.
Se fosse erro no viewstate, a excepção era lançada aquando a entrada do pedido (!?). certo?

áááá caralhassssssss

Posted (edited)
18 horas atrás, migueldesousa disse:

JaimeASV, és capaz de ter razão. Tambem já não olho para asp.net há algum tempo e o primeiro erro é algo semelhante ao que me recordo de erros do viewstate.. mas o ultimo pedido no stack trace mostra que é no acesso á bd.
Se fosse erro no viewstate, a excepção era lançada aquando a entrada do pedido (!?). certo?

Certo, não tenho a certeza mas pode depender de como ele tem aquilo programado. Se tiver aquelas conexões feitas em paginas asp.net pode dar o erro, não sei, estou só a especular.

Apenas digo isto porque ele diz que tem pedidos de ajax, e parece me mesmo que aquilo fica ali a fazer pedidos ate o view state ir à vida.

Edited by JaimeASV
Posted (edited)
1 hora atrás, 999ANDRE999 disse:

boas,

E como resolvo a expiração do view state da pagina, da sessão de utlizador e da conexão á base de dados?

Configuras mais tempo de expiração no web.config.

Poderia ajudar se pusesses o código aqui para dar uma vista de olhos :).

Experimenta isto:

<configuration> <system.web> <sessionState timeout="20"></sessionState> </system.web> </configuration>

Edited by JaimeASV
Posted (edited)
42 minutos atrás, JaimeASV disse:

Configuras mais tempo de expiração no web.config.

Poderia ajudar se pusesses o código aqui para dar uma vista de olhos :).

Experimenta isto:

<configuration> <system.web> <sessionState timeout="20"></sessionState> </system.web> </configuration>

no ficheiro web.config coloquei assim:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
    <sessionState timeout="20"></sessionState>
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        validate="false" />
    </httpHandlers>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
      </assemblies>
      <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </buildProviders>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
  </system.webServer>
</configuration>
Edited by 999ANDRE999
Posted
Em 27/10/2016 às 13:02, 999ANDRE999 disse:
<asp:Panel ID="Panel_Search_Project" runat="server" HorizontalAlign="Center" ScrollBars="Auto" EnableViewState="True"> <p> &nbsp;&nbsp;&nbsp;&nbsp; </p> </asp:Panel>

 

Primeiro começava por retirar isto, parece-me que tens um Panel a mais ai. Substituía por <p> &nbsp;&nbsp;&nbsp;&nbsp; </p>.

Se não resolver, ou se quiseres põe já no Web.Config:

<configuration>
  <appSettings>
      <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
      <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
  </appSettings>
<configuration>

De resto nada me salta à vista, mas é como já disse, ASP.NET já a algum tempo que não vejo 🙂

Posted
1 minuto atrás, JaimeASV disse:

Primeiro começava por retirar isto, parece-me que tens um Panel a mais ai. Substituía por <p> &nbsp;&nbsp;&nbsp;&nbsp; </p>.

Se não resolver, ou se quiseres põe já no Web.Config:


<configuration>
  <appSettings>
      <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
      <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
  </appSettings>
<configuration>

De resto nada me salta à vista, mas é como já disse, ASP.NET já a algum tempo que não vejo 🙂

muito obrigado. consegues só explicar-me o que fazem esses dois key?

Posted (edited)
15 minutos atrás, 999ANDRE999 disse:

muito obrigado. consegues só explicar-me o que fazem esses dois key?

De cabeça tem haver com o o tamanho dos forms, keys e jsons que o .NET transfere entre pedidos.

Mais especificamente, dá uma vista de olhos por aqui. https://msdn.microsoft.com/en-us/library/hh975440(v=vs.120).aspx

Eu adicionava na mesma o seguinte no Web.Config caso seja problemas de sessões.

<configuration> 
  <system.web> 
    <sessionState timeout="20"></sessionState> 
  </system.web> 
</configuration>
Edited by JaimeASV
Posted (edited)
30 minutos atrás, JaimeASV disse:

De cabeça tem haver com o o tamanho dos forms, keys e jsons que o .NET transfere entre pedidos.

Mais especificamente, dá uma vista de olhos por aqui. https://msdn.microsoft.com/en-us/library/hh975440(v=vs.120).aspx

Eu adicionava na mesma o seguinte no Web.Config caso seja problemas de sessões.


<configuration> 
  <system.web> 
    <sessionState timeout="20"></sessionState> 
  </system.web> 
</configuration>

Ok obrigado. 😁 

eu vou testar durante o dia e dou feedback 👍

 

EDIT:

o meu ficheiro web.conf ficou assim:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
    <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
  </appSettings>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
    <sessionState timeout="20"></sessionState>
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        validate="false" />
    </httpHandlers>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
      </assemblies>
      <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </buildProviders>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
  </system.webServer>
</configuration>
Edited by 999ANDRE999
Posted (edited)
1 hora atrás, 999ANDRE999 disse:

eu vou testar durante o dia e dou feedback 👍

Espero que funcione :).

Só uma pergunta, durante quanto tempo tencionas deixar a fazer pedidos ajax?

Se pretenderes mais de 20 minutos, precisas de mudar o valor da configuração. (isto se for a razão :P)

Edited by JaimeASV
Posted (edited)

os pedidos ajax estão praticamente 24 sob 24h.

voltou a estoirar 😕 :

Server Error in '/' Application.

An operation is already in progress.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: An operation is already in progress.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: An operation is already in progress.]
   Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlConnector.cs:1592
   Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:973
   Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:962
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +15
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +275
   Logistics_list_of_material.refresh_logistics_table() +460
   Logistics_list_of_material.Page_Load(Object sender, EventArgs e) +116
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

EDIT:

Esta pagina está sempre aberta num ecrã para se poder ver pedidos entrarem na gridview.

Edited by 999ANDRE999
Posted
8 minutos atrás, 999ANDRE999 disse:

os pedidos ajax estão praticamente 24 sob 24h.

voltou a estoirar 😕 :


Server Error in '/' Application.

An operation is already in progress.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: An operation is already in progress.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: An operation is already in progress.]
   Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlConnector.cs:1592
   Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:973
   Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) in d:\pginstaller.auto\Npgsql.windows\src\Npgsql\NpgsqlCommand.cs:962
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +15
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +275
   Logistics_list_of_material.refresh_logistics_table() +460
   Logistics_list_of_material.Page_Load(Object sender, EventArgs e) +116
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

EDIT:

Esta pagina está sempre aberta num ecrã para se poder ver pedidos entrarem na gridview.

Será que isso não está a fazer um pedido antes de o antigo ter completado?

Posted
1 minuto atrás, JaimeASV disse:

Será que isso não está a fazer um pedido antes de o antigo ter completado?

pois também já pensei nisso. A pagina fazer refresh e o servidor demorar mais que 5 segundos a responder, e entretanto já foi enviado outro pedido e estoira. Há solução sem ser aumentar o tempo do refresh? Achas melhor aumentar os valores de:

<configuration>
	<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> 
	<add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
 </configuration>
<system.web>
    <customErrors mode="Off"/>
    <sessionState timeout="20"></sessionState>
 </system.web>
Posted
1 minuto atrás, 999ANDRE999 disse:

pois também já pensei nisso. A pagina fazer refresh e o servidor demorar mais que 5 segundos a responder, e entretanto já foi enviado outro pedido e estoira. Há solução sem ser aumentar o tempo do refresh? Achas melhor aumentar os valores de:


<configuration>
	<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> 
	<add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
 </configuration>

<system.web>
    <customErrors mode="Off"/>
    <sessionState timeout="20"></sessionState>
 </system.web>

Acho que não, se tens isso 24/h remove o sessionState. O resto deixa estar nunca aleija.
 

[MethodImpl(MethodImplOptions.Synchronized)] 
public void SomeMethod() {/* code */}

Removeste o código, mete isto a ver se funciona. Não tenho a certeza se é assim em C#, estou habituado a usar em Java, nem sei se funciona igual, mas é possivel "bloquear" mais pedidos a um método ou a um bloco de código enquanto este estiver em execução.

Vê aqui.

http://stackoverflow.com/questions/541194/c-sharp-version-of-javas-synchronized-keyword

Posted

coloco no codigo .cs? onde?

public partial class Logistics_list_of_material : System.Web.UI.Page
{
    public string username = HttpContext.Current.User.Identity.Name;//nome do utilizador

    // mostra a tabela inteira
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Request.IsAuthenticated)//não autenticado
        {
            Response.Redirect("~/Account/Login.aspx");
        }

        if (!Page.IsPostBack)//autenticado
        {
            refresh_logistics_table();

            //refresh de 5 em 5 segundos
            Response.AppendHeader("Refresh", "5");

            //configuração de permissão de escrita e leitura
            DataBase.Conecta();

            Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
            comm.CommandText = " SELECT logistics FROM users where username ILIKE '" + username + "'";
            comm.Connection = DataBase.Conn;

            Npgsql.NpgsqlDataReader rd = comm.ExecuteReader();

            if (rd.Read())
            {
                if (rd.GetBoolean(0) == false)
                {
                    GridView_logistics.HeaderRow.Cells[5].Visible = false;
                    GridView_logistics.FooterRow.Cells[5].Visible = false;
                    for (int i = 0; i < GridView_logistics.Rows.Count; i++)
                    {
                        GridViewRow row = GridView_logistics.Rows[i];
                        row.Cells[5].Visible = false;
                    }

                }

            }

            DataBase.Desconecta();
        }
    }


    public void refresh_logistics_table()
    {
        string now_min = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
        string now_max = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

        DataBase.Conecta();

        Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
        //mostra os valores na tabela do dia.
        comm.CommandText = "SELECT * FROM logistics_request WHERE date_time_request >= '" + now_min + "' AND  date_time_request < '" + now_max + "' ORDER BY delivered ASC, date_time_request DESC";
        comm.Connection = DataBase.Conn;

        Npgsql.NpgsqlDataAdapter myDataAdapter = new Npgsql.NpgsqlDataAdapter();
        myDataAdapter.SelectCommand = comm;
        DataSet myDataSet = new DataSet();
        int user_exist = myDataAdapter.Fill(myDataSet);

        Panel_gridview_logistics.Visible = true;

        GridView_logistics.DataSource = myDataSet;
        GridView_logistics.DataBind();

        DataBase.Desconecta();

        
    }

    
    protected void row_paint(object sender, GridViewRowEventArgs e)
    {
        // quando montar as linhas do tipo DADOS
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // pega os campos tipo e propriedade
            string delivered = DataBinder.Eval(e.Row.DataItem, "delivered").ToString();

            // cores para aprovação
            if (delivered == "FALSE")
                e.Row.BackColor = Color.LightPink;

            if (delivered == "TRUE")
            {
               // e.Row.Cells[5].Visible = false;
                e.Row.Cells[5].Text = "✔";
                e.Row.BackColor = Color.LightGreen;
            }
         }
    }

  protected void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView_logistics.RowDeleting += new GridViewDeleteEventHandler(gridview_RowDeleting);
        DataBase.Conecta();
        Npgsql.NpgsqlCommand comm = new Npgsql.NpgsqlCommand();
        comm.Connection = DataBase.Conn;
        string id_line = GridView_logistics.DataKeys[e.RowIndex]["line"].ToString();
        string id_time = GridView_logistics.DataKeys[e.RowIndex]["date_time_request"].ToString();

        var space = id_time.Split(' ');
        var date = space[0];

        var date2 = date.Split('-');
        var day = date2[0];
        var month = date2[1];
        var year = date2[2];

        var time = space[1];

        var time2 = time.Split(':');
        var hour = time2[0];
        var min = time2[1];
        var sec = time2[2];

        string date_form = year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec;


        string delivered = "TRUE";
        string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

        comm.CommandText = "UPDATE logistics_request SET delivered='" + delivered + "', delivered_by='" + username + "', date_time_delivery='" + now + "' WHERE date_time_request='" + date_form + "' AND line= '" + id_line + "'";
        comm.ExecuteNonQuery();

        DataBase.Desconecta();

        refresh_logistics_table();
    }
}

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.