I have used json code to call the controller/action method and convert the json format inside the project,everything worked in my localhost and my server which i had, but it was not working in some other server like US server, I don't know why it throws.
Is it cause Network or IIS confirguration or code issue? If Firewall or port issue means how to change their settings?
I have attached the code which I tried,
Class :
public class Jsonget
{
public static string jsonconvert(string url)
{
string currentsite = HttpContext.Current.Request.Url.Authority;
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
wc.Encoding = UTF8Encoding.UTF8;
var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
var requestType = uri.Scheme;
string jsonurl = requestType + "://" + currentsite + url;
var jsondata = wc.DownloadString(jsonurl);
string jsonresult = "{\"results\":" + jsondata.ToString() + "}";
return jsonresult;
}
}
Index.cshtml:
jsonurl = Url.Action("GetallPrograms", "Admin", new { Name = "testprogram" });
getjsonresult = Jsonget.jsonconvert(jsonurl);
Newtonsoft.Json.Linq.JObject programList = Newtonsoft.Json.Linq.JObject.Parse(getjsonresult);
foreach (var pgm in programList["results"])
{
<p>#((string)pgm["ProgramName"])</p>
}
AdminController:
public JsonResult GetallPrograms(string Name)
{
var programList = new List<CustomAttribute>();
BaseController bc = new BaseController();
try
{
var Exist_programs = (from n in bc.db.Programs where n.Name == Name select n).ToList();
foreach (var exist in Exist_programs)
{
programList.Add(new CustomAttribute
{
ProgramName = exist.ProgramName,
Id = exist.Id.ToString()
});
}
}
catch
{
programList.Add(new CustomAttribute
{
ProgramName ="",
Id = ""
});
}
return Json(programList, JsonRequestBehavior.AllowGet);
}
Please give suggestion to fix this?
I'm getting a "Because this call is not awaited..." on
SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
Here's the button click:
private void btnCopyAllInvoices_Click(object sender, EventArgs e)
{
//sets up a list to store the incoming invoice numbers from the DB
List<string> InvoiceNums = new List<string>();
mySqlInterface.Connect();
InvoiceNums = mySqlInterface.GetNewInvoices();
//prep the visuals
lblStatus.Text = "";
InvoicePanel.Visible = true;
progressBarInvoice.Value = 0;
progressBarInvoice.Maximum = InvoiceNums.Count;
//for each invoice collected let's copy it
InvoiceNums.ForEach(delegate(string inv)
{
if (OrderDAL.CheckOrderExist(inv))
{
// the order already exist
Order myorder = new Order();
myorder = OrderDAL.GetOrder(inv);
CopyImages(myorder, true);
OrderDAL.UpdateFulfillment(string.Format("Images Copied"), inv);
}
});
//let the user know how we did
MessageBoxButtons buttons = MessageBoxButtons.OK;
string strError = string.Format("{0} Invoices copied.", InvoiceNums.Count);
MessageBox.Show(this, strError, "Copy New Invoices", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
InvoicePanel.Visible = false;
}
Here, CopyImages is called as part of the foreach loop above.
public void CopyImages(Order order, bool CopyAllInv)
{
string baseTarget = WorkSpace.Text;
string CLhotfolderTarget = string.Empty;
//check to see if the order has been photo released. If it has add "pr" to the end of the invoice number
string prInvoice = "";
if (order.Header.SignatureLine != "null" && order.Header.SignatureChecks != "null")
{
prInvoice = "pr";
}
string PackageName = null;
string CustomerName = null;
string Phone = null;
string email = null;
string PlayerInfo = null;
string PlayerName = null;
string PlayerNumber = null;
string MainEventName = null;
string MainEventCode = null;
string CLemail = null;
//go to the DB and get the info
mySqlInterface.Connect();
bool videoPackage = mySqlInterface.VideoInfo(order.Header.InvoiceNumber, out PackageName, out CustomerName, out Phone, out email, out PlayerName, out PlayerNumber, out MainEventName, out MainEventCode);
mySqlInterface.Close();
if (videoPackage)
{
if (PackageName.Contains("Video") || PackageName.Contains("Ultimate Ripken"))
{
CLemail = MainEventCode + "_" + email.Replace("#", "_").Replace(".", "_").Replace("+", "_");
PlayerInfo = PlayerName + " " + PlayerNumber;
int template_ID = 0;
if (txtCLtemplateID.Text != "")
{
template_ID = Convert.ToInt32(txtCLtemplateID.Text);
}
//we will always need a hotfolder. So let's set and create it now
CLhotfolderTarget = txtCLhotfolder.Text + "\\toUpload\\" + CLemail;
if (!System.IO.Directory.Exists(CLhotfolderTarget))
{
// create the directory
System.IO.Directory.CreateDirectory(CLhotfolderTarget);
}
int maxImages = 7;
int package_type = 2;
string[] favoritesArray = new string[maxImages];
//populate the array of images for the video
int count = 0;
foreach (Order.InvoiceImages image in order.ImageList)
{
favoritesArray[count] = image.ImageName;
count++;
}
//let's call the API and send info to CL
SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
}
}
}
public async Task SendPostAsync(string name, string email, string phone, int photo_count, string event_name, string event_id, string dir_name, int package_type, string video_text, int template_id, string[] favoritesArray)
{
string postURL = null;
string token = null;
int delivery_method = 2;
//production
postURL = "https://search.apicall.com/photographer/customer";
token = "token xxxxxxxxxxxxxxxxxxxxx";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(postURL);
client.DefaultRequestHeaders.Add("Authorization", token);
string POSTcall = JsonConvert.SerializeObject(new { name, email, phone, photo_count, event_id, event_name, dir_name, package_type, video_text, delivery_method, template_id, favorites = favoritesArray });
//Send string to log file for debug
WriteLog(POSTcall);
StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(new Uri(postURL), stringContent);
string POSTresponse = await response.Content.ReadAsStringAsync();
WriteLog(POSTresponse);
//simplified output for debug
if (POSTresponse.Contains("error") && POSTresponse.Contains("false"))
{
lblStatus.Text = "Error Sending to CL";
}
else
{
lblStatus.Text = "Successfully added to CL";
}
}
I have an await on the HttpResponseMessage response = await client.PostAsync
If I run this one at a time, it works. But when I run this through a loop and there are a bunch back to back, I think the PostAsyncs are getting stepped on. I'm missing entires in the WriteLog.
It seems I need to do the async/awaits further upstream, right? This way I can run the whole method.
Referencing Async/Await - Best Practices in Asynchronous Programming, event handlers allow async void so refactor the code to be async all the way through.
refactor CopyImages to await the posting of the data
public async Task CopyImages(Order order, bool CopyAllInv) {
//...omitted for brevity
if (videoPackage) {
if (PackageName.Contains("Video") || PackageName.Contains("Ultimate Ripken")) {
//...omitted for brevity
await SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
}
}
}
And update the event handler
private async void btnCopyAllInvoices_Click(object sender, EventArgs e) {
//sets up a list to store the incoming invoice numbers from the DB
List<string> InvoiceNums = new List<string>();
mySqlInterface.Connect();
InvoiceNums = mySqlInterface.GetNewInvoices();
//prep the visuals
lblStatus.Text = "";
InvoicePanel.Visible = true;
progressBarInvoice.Value = 0;
progressBarInvoice.Maximum = InvoiceNums.Count;
//for each invoice collected let's copy it
foreach(string inv in InvoiceNums) {
if (OrderDAL.CheckOrderExist(inv)) {
// the order already exist
Order myorder = OrderDAL.GetOrder(inv);
await CopyImages(myorder, true);
OrderDAL.UpdateFulfillment(string.Format("Images Copied"), inv);
}
}
//let the user know how we did
MessageBoxButtons buttons = MessageBoxButtons.OK;
string strError = string.Format("{0} Invoices copied.", InvoiceNums.Count);
MessageBox.Show(this, strError, "Copy New Invoices", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
InvoicePanel.Visible = false;
}
I would also advise against creating a HttpClient for each post request. Extract that out and use a single client.
static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
var postURL = "https://search.apicall.com/photographer/customer";
var token = "token xxxxxxxxxxxxxxxxxxxxx";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(postURL);
client.DefaultRequestHeaders.Add("Authorization", token);
return client
});
public async Task SendPostAsync(string name, string email, string phone, int photo_count, string event_name, string event_id, string dir_name, int package_type, string video_text, int template_id, string[] favoritesArray)
{
var postURL = "https://search.apicall.com/photographer/customer";
int delivery_method = 2;
string POSTcall = JsonConvert.SerializeObject(new { name, email, phone, photo_count, event_id, event_name, dir_name, package_type, video_text, delivery_method, template_id, favorites = favoritesArray });
//Send string to log file for debug
WriteLog(POSTcall);
StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.Value.PostAsync(new Uri(postURL), stringContent);
string POSTresponse = await response.Content.ReadAsStringAsync();
WriteLog(POSTresponse);
//simplified output for debug
if (POSTresponse.Contains("error") && POSTresponse.Contains("false")) {
lblStatus.Text = "Error Sending to CL";
} else {
lblStatus.Text = "Successfully added to CL";
}
}
public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.
I have asked a previous question on SO with regards to the Sony Camera API and I did get some help but I am still having a problem. I found the following library https://github.com/kazyx/kz-remote-api that someone made to use with the Sony Camera API but I had to make changes to it to work with a WPF app as it was optimized for windows store apps.
I am now resorting to do everything myself but I am unsure if I need to attach a Camera API file to my solution and if I do where can I find the exact file because the one the API file that I downloaded only has files for Android and iOS in which won't help me.
I finally got my thing working and I tried to put it in such a manner so that it is easily understandable. If anyone would like my Sony Library that I wrote that please let me know as I also tried the Kazyx library and that didn't work for me.
My code is below.
private string cameraURL;
private bool recModeActive;
public void ControlCamera(string cameraResp)
{
cameraURL = string.Format("{0}/{1}", GetCameraURL(cameraResp), GetActionType(cameraResp));
}
private string CameraRequest(string cameraUrl, string cameraRequest)
{
Uri urlURI = new Uri(cameraURL);
HttpWebRequest cameraReq = (HttpWebRequest)WebRequest.Create(cameraURL);
cameraReq.Method = "POST";
cameraReq.AllowWriteStreamBuffering = false;
cameraReq.ContentType = "application/json; charset=utf-8";
cameraReq.Accept = "Accept-application/json";
cameraReq.ContentLength = cameraRequest.Length;
using (var cameraWrite = new StreamWriter(cameraReq.GetRequestStream()))
{
cameraWrite.Write(cameraRequest);
}
var cameraResp = (HttpWebResponse)cameraReq.GetResponse();
Stream cameraStream = cameraResp.GetResponseStream();
StreamReader cameraRead = new StreamReader(cameraStream);
string readCamera = cameraRead.ReadToEnd();
return readCamera;
}
public string GetCameraURL(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string cameraURL = "";
foreach (string cameraString in cameraXML)
{
string getCameraURL = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ActionList_URL>"))
{
getCameraURL = cameraString.Substring(cameraString.IndexOf('>') + 1);
cameraURL = getCameraURL.Substring(0, getCameraURL.IndexOf('<'));
}
}
return cameraURL;
}
public string GetActionType(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string actionType = "";
foreach (string cameraString in cameraXML)
{
string getType = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ServiceType>"))
{
getType = cameraString.Substring(cameraString.IndexOf('>') + 1);
actionType = getType.Substring(0, getType.IndexOf('<'));
if (actionType == "camera")
{
break;
}
}
}
return actionType;
}
public string StartRecMode()
{
string startRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "startRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = true;
return CameraRequest(cameraURL, startRecMode);
}
public string TriggerCamera()
{
string _triggerCamera = JsonConvert.SerializeObject(new Camera.StillCapture
{
method = "actTakePicture",
#params = new List<string> { },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _triggerCamera);
}
public string EchoRequest()
{
string _echoRequest = JsonConvert.SerializeObject(new Camera.TestCameraComm
{
method = "getEvent",
#params = new List<bool> { true },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _echoRequest);
}
public string StopRecMode()
{
string stopRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "stopRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, stopRecMode);
}
public string SetImageQuality()
{
string qualityReq = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "setStillSize",
#params = new List<string> { "4:3", "20M"},
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, qualityReq);
}`
String status;
IEnumerable<TwitterStatus> twitterStatus = twitterService.ListTweetsOnPublicTimeline();
foreach(String status in twitterStatus)
{
Console.WriteLine(twitterStatus);
}
Why it give can not convert string type error in foreach loop ?
this is my whole code
namespace TweetingTest
{
class Program
{
static void Main(string[] args)
{
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config
TwitterService twitterService = new TwitterService(twitterClientInfo);
if (string.IsNullOrEmpty(AccessToken) || string.IsNullOrEmpty(AccessTokenSecret))
{
//Now we need the Token and TokenSecret
//Firstly we need the RequestToken and the AuthorisationUrl
OAuthRequestToken requestToken = twitterService.GetRequestToken();
string authUrl = twitterService.GetAuthorizationUri(requestToken).ToString();
//authUrl is just a URL we can open IE and paste it in if we want
Console.WriteLine("Please Allow This App to send Tweets on your behalf");
//Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.
//Allow the App
Console.WriteLine("Enter the PIN from the Browser:");
string pin = Console.ReadLine();
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, pin);
string token = accessToken.Token; //Attach the Debugger and put a break point here
string tokenSecret = accessToken.TokenSecret; //And another Breakpoint here
Console.WriteLine("Write Down The AccessToken: " + token);
Console.WriteLine("Write Down the AccessTokenSecret: " + tokenSecret);
}
twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
//Console.WriteLine("Enter a Tweet");
//string tweetMessage;
//string data;
//string ListTweetsOnPublicTimeline;
//string TwitterUserStreamStatus = ListTweetsOnPublicTimeline();
//TwitterStatus=ListTweetsOnPublicTimeline();
//tweetMessage = Console.ReadLine();
//ListTweetsOnPublicTimeline = Console.ReadLine();
//TwitterStatus twitterStatus = twitterService.SendTweet(tweetMessage);
//TwitterStatus twitterStatus = twitterService.ListTweetsOnPublicTimeline();
//String status;
IEnumerable<TwitterStatus> tweets = twitterService.ListTweetsOnPublicTimeline();
foreach(var tweet in tweets)
{
Console.WriteLine(tweet);
//Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
//twitterStatus=Console.ReadLine();
}
This is my whole code on which I am working and facing just one error on foreach loop which is my lack of knowledge in C#
You will need something like this..
using TweetSharp;
TwitterService service = new TwitterService();
IEnumerable<TwitterStatus> tweets = service.ListTweetsOnPublicTimeline();
foreach (var tweet in tweets)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
Also try this code to see why it is failing.. try to debug response.StatusCode
using TweetSharp;
TwitterService service = new TwitterService();
IAsyncResult result = service.ListTweetsOnPublicTimeline(
(tweets, response) =>
{
if(response.StatusCode == HttpStatusCode.OK)
{
foreach (var tweet in tweets)
{
Console.WriteLine("{0} said '{1}'", tweet.User.ScreenName, tweet.Text);
}
}
});
More here : https://github.com/danielcrenna/tweetsharp
The object you are itterating through is of type "TwitterStatus", not string... so you are confusing it when you try to automatically cast a TwitterStatus object as a string.
Your question is very vague, so I'm going to assume your TitterStatus object has a "Text" property for the purposes of this answer.
foreach(TwitterStatus status in twitterStatus)
{
Console.WriteLine(status.Text);
}
(just replace the ".Text" with whatever property of TwitterStatus
holds the status text)