0

I have a view called DailyVisitSummary. If I select FromDate and ToDate, it will generate the report called rpt.VisitSummaryReport depending upon the selected dates.

I am using Crystal Reports to generate reports. If I run my application (on my local machine), the report is working fine. But if I check my application after deploying to a local host using IIS Server, the report is not working correctly. It is showing an error. The error which is mentioned in the below image (second one)

enter image description here

enter image description here

My VisitorsViewModel;:

 public DateTime  ? FromDate { get; set; }
 public DateTime  ? ToDate { get; set; }

My view:

 <div class="form-group">
 @Html.LabelFor(model => model.FromDate)
 @Html.TextBoxFor(model => model.FromDate, new { @class = "form-control", type = "text" })
 </div>
 <div class="form-group">
 @Html.LabelFor(model => model.ToDate)
 @Html.TextBoxFor(model => model.ToDate, new { @class = "form-control", type = "text" })
 </div>

My jQuery code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">    </script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

<script>
$("#FromDate").datepicker({
    dateFormat: "dd/mm/yy",
    changeMonth: true,
    changeYear: true,
});

$("#ToDate").datepicker({
    dateFormat: "dd/mm/yy",
    changeMonth: true,
    changeYear: true,
});</script>

My controller code:

public ActionResult VisitSummaryReport()
{
    return View();
}

[HttpPost]
public ActionResult GetDates(VisitorsViewModel VisitorsVM)
{
        var fromdt = Convert.ToDateTime(VisitorsVM.FromDate);
        var todt = Convert.ToDateTime(VisitorsVM.ToDate);
        SqlConnection con = new SqlConnection(@"Data Source=192.168.0.73\SQLEXPRESS,14330;Initial Catalog=WafeERP_NEW;User ID=sa;Password=wafewin;");

        DataTable dt = new DataTable();

        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from View_VisitorsForm where  VisitingDate >='" + fromdt  +"'and VisitingDate <= '" + todt  +"'", con);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
        }
        catch (Exception ex)
        {
            throw;
        }

        ReportDocument rpt = new ReportDocument();  
        rpt.Load(Server.MapPath("~/Areas/Sales/CrystalReports/rpt_VisitSummaryCrystalReport.rpt"));
        rpt.SetDataSource(dt);

        Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

        return File(stream, "application/pdf");
}

I tried my level best to explain my issue. Any one understand my issue and help me to resolve this issue.

Thanks in advance.

Susan
  • 421
  • 2
  • 6
  • 21
  • 2
    Why are your properties `string` instead of `DateTime`? –  Aug 09 '16 at 05:41
  • ok i have a try and let you to know stephen – Susan Aug 09 '16 at 05:42
  • @StephenMuecke you ask me to chnage my property as String from DateTime Right – Susan Aug 09 '16 at 05:44
  • Based on your edit, your properties are `DateTime`. The error is occurring because one or both are `null` (debug your code). And there is no point using `Convert.ToDateTime()` if the property is already `DateTime`) –  Aug 09 '16 at 05:49
  • @StephenMuecke now i change the model property to string – Susan Aug 09 '16 at 05:51
  • No, It should be `DateTime` (and not nullable) –  Aug 09 '16 at 05:52
  • mhm okok then i remove that convert.ToDateTime() and check again and let you knoe – Susan Aug 09 '16 at 05:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120471/discussion-between-stephen-muecke-and-susan). –  Aug 09 '16 at 05:54

3 Answers3

1

You have a number of issues.

First, assuming you want the user to select both dates in the view, your properties should be DateTime (not nullable) and include a@Html.ValidationMessageFor() for each property Then in the POST method, start with

if(!ModelState.IsValid())
{
    return View(VisitorsVM);
}

But more importantly, your opening yourself to SQL injection attacks where a malicious user can gain access to your database, or simply delete it, and I recommend you read these answers and other articles on SQL Injection attacks. You need to modify you code to use parameterized queries

SqlConnection con = new SqlConnection(.....);
DataTable dt = new DataTable();
try
{
    SqlCommand command = new SqlCommand();
    command.CommandText = "Select * from View_VisitorsForm where VisitingDate >= @fromDate and VisitingDate <= @toDate";
    command.Parameters.Add("@fromDate", System.Data.SqlDbType.Date).Value = VisitorsVM.FromDate;
    command.Parameters.Add("@toDate", System.Data.SqlDbType.Date).Value = VisitorsVM.ToDate;
    command.Connection = con;
    // con.Open();
    SqlDataAdapter adp = new SqlDataAdapter(command); 
    adp.Fill(dt);
}

Note there is no need to open the connection - the .Fill() method will open and close it, but if you do use it, then you need to call con.Close(); after .Fill()

I would also recommend that this code be in a separate service rather than in a controller method

Side note: There is no need for new { type = "text" }) in you view. The TextBoxFor() method already adds the type="text" attribute so your just overwriting the existing value.

Community
  • 1
  • 1
0

I think there is a problem while passing DateTime to SqlCommand. For this you can check it from here

I hope it would resolved your problem.

Community
  • 1
  • 1
Lalit Rajput
  • 271
  • 2
  • 5
  • 23
0

You need to convert string value to SQL datetime. For necessary date conversion pattern you can find it in here.

SqlCommand cmd = new SqlCommand("Select * from View_VisitorsForm where  VisitingDate >=CONVERT(datetime,'" + fromdt  +"', 3) and VisitingDate <= CONVERT(datetime,'" + todt  +"', 3)", con);

I choose 3 because you declare your datetime format as 'dd/mm/yyyy' in your client.

omer faruk
  • 350
  • 4
  • 13
  • omer its not working . im getting this error Conversion failed when converting date and/or time from character string. – Susan Aug 09 '16 at 07:04
  • @Susan can you try this conversion pattern id `Select * from View_VisitorsForm where VisitingDate >=CONVERT(datetime,'10/10/2015', 103) and VisitingDate <= CONVERT(datetime,'10/10/2017', 103)` – omer faruk Aug 09 '16 at 09:06
  • Actually omer my date format in db is 2011-07-01 15:17:33.357 while retrieving date from db it changing the format and the format is mention in the below image. [![enter image description here][3]][3] [3]: http://i.stack.imgur.com/2vNnd.jpg . i think this only creating problem – Susan Aug 09 '16 at 11:38
  • Problem is that your date format for column in database is different than in query date format. I mean your column datetime format is **yyyy-mm-dd hh:MM:ss** and you are trying to query it with date in format **dd/mm/yyyy**. When SQL Server tries to convert automatically, it fails because SQL Server expecting either the same datetime format for query or convertible datetime format. – omer faruk Aug 09 '16 at 12:54
  • Yes how to convert the format of date in sql query while retrieving from database – Susan Aug 09 '16 at 13:00
  • There is no need to convert your column date format, instead convert your query date format. To do that you need to find suitable conversion id. If you say that your date format is **2011-07-01 15:17:33.357**, either you should try 120 or 121. I will write down both of them. `Select * from View_VisitorsForm where VisitingDate >=CONVERT(datetime,'10/10/2015', 120) and VisitingDate <= CONVERT(datetime,'10/10/2017', 120)` OR `Select * from View_VisitorsForm where VisitingDate >=CONVERT(datetime,'10/10/2015', 121) and VisitingDate <= CONVERT(datetime,'10/10/2017', 121)` – omer faruk Aug 09 '16 at 18:48
  • Ok i have a try Omer and let you know – Susan Aug 10 '16 at 03:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120560/discussion-between-susan-and-omer-faruk). – Susan Aug 10 '16 at 03:50
  • @moner I want to get the date from( From date and To date) view. Depending upon the date i have to retrieve the data from database – Susan Aug 10 '16 at 03:54