Reputation: 53
I am new to json and web api. I created a service called AdminService which has a get method. Kindly see below the get method:
[Route("{iUserId:long}/{iSegmentId:long}/GetUserSegmentItemBySegmentIdAndUserId")]
public IEnumerable<spADGetUserSegmentItemBySegmentIdAndUserId> GetUserSegmentItemBySegmentIdAndUserId(long iUserId, long iSegmentId)
{
using (ADMINEntities context = new ADMINEntities())
{
var usibsu = context.spADGetUserSegmentItemBySegmentIdAndUserId(iUserId, iSegmentId);
if (usibsu != null) return usibsu.ToList();
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
}
The service is working correctly. Now, I have another service called TestService in which i want to call the get method i created in the adminservice. Below is my code:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Newtonsoft.Json;
using NPAService.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace NPAService.Controllers
{
public class HomeController : Controller
{
private string ServiceURLBase = ConfigurationManager.AppSettings["AdminUrl"];
public ActionResult Index()
{
return View();
}
private void MoveImageFiles()
{
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Reports/"));
List<String> FileNames = new List<string>();
for (int i = 0; i < dirInfo.GetFiles().Length; i++)
{
FileNames.Add(dirInfo.GetFiles()[i].FullName);
}
for (int i = 0; i < FileNames.Count; i++)
{
FileInfo fileInfo = new FileInfo(FileNames[i]);
//Delete file if it is older than five minutes
if (DateTime.Now.Subtract(fileInfo.CreationTime).TotalMinutes > 1.0)
{
System.IO.File.Delete(fileInfo.FullName);
//if the file exists at the destination folder, delete it as well
if (System.IO.File.Exists(Server.MapPath("~/Home/images/") + fileInfo.Name))
{
System.IO.File.Delete(Server.MapPath("~/Home/images/") + fileInfo.Name);
}
}
else //Copy file to where it can get displayed on the report if it is less than 5 minute old
{
if (!System.IO.File.Exists(Server.MapPath("~/Home/images/") + fileInfo.Name))
{
System.IO.File.Copy(fileInfo.FullName, Server.MapPath("~/Home/images/") + fileInfo.Name);
}
}
}
}
public string GetUserDataSegment(long iUserId, long iSegmentId)
{
string ListString = string.Empty;
var userdata = new UserData();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ServiceURLBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(iUserId + "/" + iSegmentId + "/GetUserSegmentItemBySegmentIdAndUserId").Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<UserData>(data);
//foreach (var str in data)
//{
//ListString = str.MyList;
//if (iSegmentId == 1) //'Depot'
//{
// ListString = ("iRegionId IN (" + str.MyList + ")");
//}
//else if (iSegmentId == 2) //'BDC'
//{
//}
//else if (iSegmentId == 3) //'LPGMC'
//{
//}
//else if (iSegmentId == 4) //'Region'
//{
// ListString = ListString + (" and iRegionId IN (" + str.MyList + ")");
//}
//else if (iSegmentId == 5) //'OMC'
//{
// ListString = ListString + (" and iOMCId IN (" + str.MyList + ")");
// ListString = "";
//}
//else if (iSegmentId == 6) //'Zone'
//{
//}
//}
}
}
return ListString;
}
[System.Web.Mvc.HttpGet]
public ActionResult OutletReportListing(long lngCompanyId, string strszITSfromPersol,
string strsQuery1, string strsQuery2, string strsQuery3, string strsQuery4,
string strPicHeight, string strPicWeight, string strCompany, long iUserId, string type)
{
string Username = Convert.ToString(ConfigurationManager.AppSettings["username"]);
string Password = Convert.ToString(ConfigurationManager.AppSettings["password"]);
string Servername = Convert.ToString(ConfigurationManager.AppSettings["DSN"]);
string Databasename = Convert.ToString(ConfigurationManager.AppSettings["databasename"]);
//GetUserDataSegment(iUserId, 5).Wait();
//var myObjList = JSON.Deserialize<List<GetUserDataSegment>>(iUserId, 5);
//var objResponse1 =
// JsonConvert.DeserializeObject<List<UserData>>(iUserId, 5);
string strOMC = GetUserDataSegment(iUserId,5);
string strRegion = GetUserDataSegment(iUserId, 4);
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("~/Reports/rptNPAOutletListing.rpt"));
reportdocument.SetDatabaseLogon(Username, Password, Servername, Databasename);
reportdocument.SetParameterValue("@iCompanyId", lngCompanyId);
reportdocument.SetParameterValue("@szITSfromPersol", strszITSfromPersol);
reportdocument.SetParameterValue("@szQuery1", strsQuery1);
reportdocument.SetParameterValue("@szQuery2", strsQuery2);
reportdocument.SetParameterValue("@szQuery3", strOMC); //strOMC
reportdocument.SetParameterValue("@szQuery4", strRegion); //strRegion
reportdocument.SetParameterValue("@szPicHeight", strPicHeight);
reportdocument.SetParameterValue("@szPicWeight", strPicWeight);
reportdocument.SetParameterValue("@szCompany", strCompany);
ExportFormatType formtType = ExportFormatType.HTML40;
string ExportName = "NPAReport.html";
string ExportMimeType = "text/html";
if (type.Trim().ToLower().Equals("view"))
{
formtType = ExportFormatType.HTML40;
ExportName = "NPAReport.html";
ExportMimeType = "text/html";
}
else if (type.Trim().ToLower().Equals("pdf"))
{
formtType = ExportFormatType.PortableDocFormat;
ExportName = "NPAReport.pdf";
ExportMimeType = "application/pdf";
}
else if (type.Trim().ToLower().Equals("doc"))
{
formtType = ExportFormatType.WordForWindows;
ExportName = "NPAReport.doc";
ExportMimeType = "application/msword";
}
else if (type.Trim().ToLower().Equals("rtf"))
{
formtType = ExportFormatType.RichText;
ExportName = "NPAReport.rtf";
ExportMimeType = "application/rtf";
}
else if (type.Trim().ToLower().Equals("xls"))
{
formtType = ExportFormatType.Excel;
ExportName = "NPAReport.xls";
ExportMimeType = "application/vnd.ms-excel";
}
reportdocument.ExportToDisk(formtType, Server.MapPath("~/Reports/" + ExportName));
MoveImageFiles();
return File(Server.MapPath("~/Reports/" + ExportName), ExportMimeType);
}
}
}
As you can see, i want to generate a report file in my api project. But the first error i am getting is: cannot convert from 'System.Threading.Tasks.Task' to 'string'
I have done a lot of research but none does not seem to work. Any help or explanation would be appreciated. Thank you.
Upvotes: 1
Views: 7116
Reputation: 2042
response.Content.ReadAsStringAsync();
Async calls return Task<T>
. When you want to read the string you call .Result
property and you get the string. There is also a way to make async call synchronous. When you call an async method, your method gets out of execution and your method's caller continues execution. When async call completes, then your method continues its execution right after async method. Also since you call async method from GetUserDataSegment
method, it also needs to be labeled as async
.
Upvotes: 2