Can't find way to debug Internal Server Error (500) caused by new class - botframework

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`

I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

Related

Response status code does not indicate success: '400' ('Bad request')

i want to POST data to API in my android xamarin app using refit i've tested the API at Postman and it's working fine but at android app i'm getting exception Bad request.
Here is my android code i added the interface and the model i don't know what is the problem .
public interface RequestAPI
{
[Post("/request")]
Task<create_request> submit([Body] create_request request);
}
requestAPI= RestService.For<RequestAPI>("http://courier-magconsulting.azurewebsites.net/api");
button.Click += async delegate
{
try
{
create_request request = new create_request();
request.PickUpPhone = "7664554";
request.DownPayment = 89;
request.DeliveryFees = 56.8;
request.Note = "i need a help!";
request.RequestID = 88; // replace the value yourself
request.DekiveryLocationLatitude = 2323;
request.DeliveryLocationLongitude = 232;
request.PickUpLocationLatitude = 898;
request.PickUpLocationLongitude = 1123;
BroadcastType type = new BroadcastType();
type.Name = "All";
type.ID = 60; // replace the value yourself
request.BroadcastType = type;
Cargosize size = new Cargosize();
size.Name = "Small";
size.ID = 1; // replace the value yourself
request.Cargosize = size;
Cargoweight weight = new Cargoweight();
weight.Name = "Large";
weight.ID = 2; // replace the value yourself
request.CargoWeight = weight;
Sender sender_ = new Sender();
sender_.Name = "Ahmad";
sender_.SenderID = 1; // replace the value yourself
sender_.Phone = "8788";
sender_.SocialID = "8787";
sender_.RatingAvg = 5;
SenderStatus status = new SenderStatus();
status.ID = 1;
status.Name = "Active";
sender_.Senderstatus = status;
request.Sender = sender_;
create_request result = await requestAPI.submit(request);
Toast.MakeText(this, "Request created", ToastLength.Long).Show();
}
catch(Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
};

Silverlight some wcf problems

I have created a WCF Service which is called many times,
An example of a call
This Service will do a call to a Database. Lets say in my Client I do have a List with 200 Values. Every Value will match a Database Entry. Every Database Entry does have 10 Values. Now what I do is the following. I select some of the list entrys and call in a loop the WCF Service.
I have 2 Issues
First: the UI will hang for that time the WCF Calls are made
Second: The data will come back step by step, how can I collect them and send it back when all calls are completed?
Please excuse any typos I made, my english is not the best.
Here is my source code
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[OperationContract]
public List<string> GetData(string sWert1, string sWert2)
{
List<string> realtimanswer = new List<string>();
string applicationPath = HostingEnvironment.MapPath("~/Configuration");
cIniReader _ini = new cIniReader(applicationPath + #"\config.ini");
string connectionString = _ini.ReadString("Database", "ConnectionString", "");
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
OracleCommand cmd = connection.CreateCommand();
cmd = new OracleCommand("GETDATA", connection);
cmd.Parameters.Clear();
OracleParameter param1 = new OracleParameter("PI_Wert1", OracleDbType.Varchar2);
OracleParameter param2 = new OracleParameter("PI_Wert2", OracleDbType.Varchar2);
OracleParameter param3 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param4 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param5 = new OracleParameter("PO_Wert4", OracleDbType.Int16);
param1.Value = sWert1;
param2.Value = sWert2;
param1.Direction = System.Data.ParameterDirection.Input;
param1.Size = 4096;
param2.Direction = System.Data.ParameterDirection.Input;
param2.Size = 4096;
param3.Direction = System.Data.ParameterDirection.Output;
param3.Size = 4096;
param4.Direction = System.Data.ParameterDirection.Output;
param4.Size = 4096;
param5.Direction = System.Data.ParameterDirection.Output;
param5.Size = 4096;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(param3);
cmd.Parameters.Add(param4);
cmd.Parameters.Add(param5);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//cmd.CommandTimeout = 30;
int test = cmd.ExecuteNonQuery();
string returnCode = cmd.Parameters[17 - 1].Value.ToString();
if (returnCode == "OK")
{
string sErg1 = cmd.Parameters[3 - 1].Value.ToString();
realtimanswer.Add(sErg1);
string sErg2 = cmd.Parameters[4 - 1].Value.ToString();
realtimanswer.Add(sErg2);
string sErg3 = cmd.Parameters[5 - 1].Value.ToString();
realtimanswer.Add(sErg3);
string sErg4 = cmd.Parameters[6 - 1].Value.ToString();
realtimanswer.Add(sErg4);
string sErg5 = cmd.Parameters[7 - 1].Value.ToString();
realtimanswer.Add(sErg5);
}
}
catch (Exception exp)
{
cDebugLog.Log("Error in Function: GetData " + exp.Message + " StackTrace: " + exp.StackTrace);
connection.Close();
}
connection.Close();
return realtimanswer;
}
}
I call this with this Code
void Button1_Click(object sender, EventArgs e)
{
busyRealTimeViewPage.IsBusy = true;
try
{
string url = Application.Current.Host.Source.AbsoluteUri;
url = url.Replace("/ClientBin/ICWeb.xap", "/DBService.svc");
var proxy_GetRealTime_DBService = new DBServiceReference.DBServiceClient();
proxy_GetRealTime_DBService.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
proxy_GetRealTime_DBService.GetDataCompleted += new EventHandler<DBServiceReference.GetDataCompletedEventArgs>(proxy_GetRealTime_DBService_GetDataCompleted);
for (int i = 0; i < lstRealtime.Items.Count; i++)
{
if ((lstRealtim.ItemsSource as ObservableCollection<ListOfData>)[i].IsSelected == true)
{
object[] w_toread = new object[5];
string sWrk = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
w_toread[0] = sDat;
w_toread[1] = sDat + "_DE";
w_toread[2] = sDat + "_FR";
proxy_GetRealTime_DBService.GetDataAsync(w_toread[1].ToString(), "current", w_toread[1]);
proxy_GetRealTime_DBService.GetDataAsync(w_toread[2].ToString(), "current", w_toread[2]);
}
}
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Error in Function: Button1_Click " + exp.Message + " StackTrace: " + exp.StackTrace);
}
and now here is the rest of it
void proxy_GetRealTime_DBService_GetDataCompleted(object sender, DBServiceReference.GetMarqueeDataCompletedEventArgs e)
{
try
{
string help = e.UserState.ToString();
string sWrktoView = cStringFunctions.Left(e.UserState.ToString(), help.Length - 3);
// string sWrktoView = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
string sWrktoViewDE = sWrktoView + "_DE";
string sWrktoViewFR = sWrktoView + "_FR";
if ((sWrktoViewDE == e.UserState.ToString()) || (sWrktoViewFR == e.UserState.ToString()))
{
if (!(toView.Any(wrk => wrk.Workgroup == sWrktoView)))
{
if (sWrktoViewDE == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13], sWrktoViewFR, "", "", "", "", "", "", "", "", "", "", "", "", "", ""));
}
if (sWrktoViewFR == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, "", "", "", "", "", "", "", "", "", "", "", "", "", "", sWrktoViewFR, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13]));
}
}
}
if (sWrktoViewFR == e.UserState.ToString())
{
var wrkFR = toView.FirstOrDefault(x => x.WorkgroupFR == sWrktoViewFR);
if (wrkFR != null)
{
wrkFR.WorkgroupFR = sWrktoViewFR;
wrkFR.erg1FR = e.Result[0];
wrkFR.erg2FR = e.Result[1];
wrkFR.erg3FR = e.Result[2];
wrkFR.erg4FR = e.Result[3];
wrkFR.erg5FR = e.Result[4];
// fill with other data
}
}
if (sWrktoViewDE == e.UserState.ToString())
{
var wrkDE = toView.FirstOrDefault(x => x.WorkgroupDE == sWrktoViewDE);
if (wrkDE != null)
{
wrkDE.WorkgroupDE = sWrktoViewDE;
wrkDE.erg1DE = e.Result[0];
wrkDE.erg2DE = e.Result[1];
wrkDE.erg3DE = e.Result[2];
wrkDE.erg4DE = e.Result[3];
wrkDE.erg5DE = e.Result[4];
// fill with other Data
}
}
dgridRealTimeView.ItemsSource = null;
dgridRealTimeView.ItemsSource = toView;
busyRealTimeViewPage.IsBusy = false;
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Methode: proxy_GetRealTime_DBService_GetDataCompleted: " + exp.Message + " StackTrace: " + exp.StackTrace);
}
}
I hope someone can help me out.
Regards
Martin
This call
for (int i = 0; i < lstRealtime.Items.Count; i++)
can take a long time if the there are a lot of items in the list.
You should consider creating a new method on the WCF Service to do all the operations and then returning the result.
public List<string> GetData(string[] sWert1, string[] sWert2)
{
}

C# - WebRequestMethods.Ftp.DownloadFile not working (timeout)

Good afternoon everyone.
I'm trying to download a few files from a FTP server and I don't know why this isn't working, because the same code worked before. Now when i run the service I get the following error:
Error 1053: The service did not respond to the start or control request in a timely fashion
I've tried doing other Methods like GetFileSize or even the DeleteFile that it's suppose to execute after the DownloadFile and they work, but this one isn't and i can't figure out why. Any ideas? My code is below, many thanks!
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(server + file));
reqFTP.Credentials = new NetworkCredential(username, password);
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
reqFTP.Timeout = -1;
FtpWebResponse response2 = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream2 = response2.GetResponseStream();
FileStream writeStream = new FileStream(folder + file, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream2.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream2.Read(buffer, 0, Length);
}
writeStream.Close();
response2.Close();
try
{
string uri2 = server + file;
Uri serverUri2 = new Uri(uri);
if (serverUri2.Scheme != Uri.UriSchemeFtp)
{
return;
}
FtpWebRequest reqFTP2;
reqFTP2 = (FtpWebRequest)FtpWebRequest.Create(new Uri(server + file));
reqFTP2.Credentials = new NetworkCredential(username, password);
reqFTP2.KeepAlive = false;
reqFTP2.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP2.UseBinary = true;
reqFTP2.Proxy = null;
reqFTP2.UsePassive = false;
FtpWebResponse response3 = (FtpWebResponse)reqFTP2.GetResponse();
Stream responseStream3 = response3.GetResponseStream();
response3.Close();
}

Microsoft Interop Outlook c# - invalidcastexception?

Suddenly getting a System.invalidcastexception: unable to cast COM object of type 'system._object' to interface type 'Microsoft.office.interop.outlook.mailitem' ... to a program I wrote that was working fine and now BAM! Exception.
Not sure why... please note I'm a novice programmer.
Here's a snippet of coding where I'm using the Outlook things :
using Microsoft.Office.Interop.Outlook;
static Microsoft.Office.Interop.Outlook.Application app = null;
static _NameSpace ns = null;
static MailItem item = null;
static MAPIFolder inboxFolder = null;
static MAPIFolder dest = null;
static void SendMail(string mailSubject, string htmlMailBody, string mailTo)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
outlookNS.Logon(Missing.Value, Missing.Value, true, true);
MailItem oMsg = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
oMsg.To = mailTo;
oMsg.Recipients.ResolveAll();
StreamReader sr = new StreamReader(#"C:\Users\" + WindowsIdentity.GetCurrent().Name.Split('\\')[1] + #"\AppData\Roaming\Microsoft\Signatures\Default.htm");
string signature = sr.ReadToEnd();
oMsg.Subject = mailSubject;
oMsg.HTMLBody = htmlMailBody + "<br><br>" + signature + "</font>";
oMsg.Save();
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
oMsg = null;
outlookNS = null;
outlookApp = null;
}
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
#region match - convert - extract
foreach (string tifFile in Directory.GetFiles(workFolder, "*.tif", SearchOption.TopDirectoryOnly))
{
string currentFile = Path.GetFileNameWithoutExtension(tifFile);
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
//##############CODE CRASHES HERE##############
item = (MailItem)inboxFolder.Items[i];
// item = inboxFolder.Items[i];
if (item.Body != "")
{
if ((item.Body.Contains("Box Number =")) && (item.Body.Contains("Contract ID = ")) && (item.Body.Contains("Branch = ")) && (item.Body.Contains(currentFile.Replace('_', '/'))))
{
// matchFound = true;
MailStack current = new MailStack();
Console.WriteLine("________________________");
Console.WriteLine("File matched \t\t:\t" + currentFile + ".tif");
I've looked around but can't make much sense of the answers available.
any help appreciated.
Try this...
item = inboxFolder.Items[i] as MailItem;
if (item != null)
{
// ...
}

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

Resources