1

SQLデータベース内のデータをカウントする機能を持つWebサービスを作成しました。ここに私のWebService.asmxのコードがあります:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public int SalesNumberMonth(int i)
    {
        int total = 0;
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
        try
        {
            string request = "SELECT * FROM sales_Ventes V INNER JOIN sys_AnneesFiscales A ON V.AnneeFiscale = A.Code INNER JOIN sys_Mois M ON V.Mois = M.Code WHERE M.Code='" + i + "'" + " AND Active = 'true'";
            connection.Open();
            SqlCommand Req = new SqlCommand(request, connection);

            SqlDataReader Reader = Req.ExecuteReader();
            while (Reader.Read())
            {
                total++;
            }
            Reader.Close();
        }
        catch
        {

        }
        connection.Close();
        return total;
    }
}

そしてここに私のscript.js:

var sin = [], cos = [];
for (var i = 1; i < 13; i += 1) {
    GestionPro.WebService1.SalesNumberMonth(i,  function (e) { sin.push([i, e]); }  ,function (response) { alert(response); }  );
    cos.push([i, 2]);
}
var plot = $.plot($("#mws-test-chart"),
       [{ data: sin, label: "Sin(x)²", color: "#eeeeee" }, { data: cos, label: "Cos(x)", color: "#c5d52b"}], {
           series: {
               lines: { show: true },
               points: { show: true }
           },
           grid: { hoverable: true, clickable: true }
       });

私の問題はこの行にあります:

GestionPro.WebService1.SalesNumberMonth(i,  function (e) { sin.push([i, e]); }  ,function (response) { alert(response); }  );

2つの関数を入れ替えると、アラートは適切に表示されますが、この順序では、sin[]に関数の値を追加できません。私は何かを逃す必要がありますが、何がわからない...

4

1 に答える 1

5

There are enormously lots of issues with your code:

  • You are triggering AJAX requests in the for loop. It would be far more optimal to trigger a single AJAX request that will return the entire result. It's always better to send fewer requests that send more data rather than lots of small AJAX requests
  • You are using SELECT * and then counting on the client code in a loop instead of using the COUNT SQL aggregate function
  • You are not disposing properly any of the IDisposable resources such as database connections, commands and readers
  • You are using a string concatenation to build your SQL query instead of using parametrized queries
  • You are not taking into account the asynchronous nature of AJAX

The issues being mentioned, let's start by fixing them.

Let's first fix the server side code:

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public int[] SalesNumbersMonths(int[] months)
    {
        // Could use LINQ instead but since I don't know which version
        // of the framework you are using I am providing the naive approach
        // here. Also the fact that you are using ASMX web services which are
        // a completely obsolete technology today makes me think that you probably
        // are using something pre .NET 3.0
        List<int> result = new List<int>();
        foreach (var month in months)
        {
            result.Add(SalesNumberMonth(month));
        }
        return result.ToArray();
    }


    [WebMethod]
    public int SalesNumberMonth(int i)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString))
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT COUNT(*) FROM sales_Ventes V INNER JOIN sys_AnneesFiscales A ON V.AnneeFiscale = A.Code INNER JOIN sys_Mois M ON V.Mois = M.Code WHERE M.Code=@Code AND Active = 'true'";  
            cmd.Parameters.AddWithValue("@Code", i);
            return (int)cmd.ExecuteScalar();
        }
    }
}

OK, you will notice now the new method that I added and which allows to calculate totals for a number of months and returning them as an array of integers to avoid wasting bandwidth in meaningless AJAX requests.

Now let's fix your client side code:

var months = [];

for (var i = 1; i < 13; i += 1) {
    months.push(i);
}

GestionPro.WebService1.SalesNumbersMonths(months, function (e) { 
    // and once the web service succeeds in the AJAX request we could build the chart:
    var sin = [],
        cos = [];

    for (var i = 0; i < e.length; i++) {
        cos.push([i, 2]);
        sin.push([i, e[i]]);
    }

    var chart = $('#mws-test-chart'),
    var data = [
        { data: sin, label: 'Sin(x)²', color: '#eeeeee' }, 
        { data: cos, label: 'Cos(x)', color: '#c5d52b' }
    ];

    var series = { 
        series: {
            lines: { show: true },
            points: { show: true }
        }
    };

    var plot = $.plot(
        chart, 
        data, 
        series, 
        grid: { hoverable: true, clickable: true }
    );

    // TODO: do something with the plot

}, function (response) { 
    // that's the error handler
    alert(response); 
});
于 2012-07-04T12:41:33.427 に答える