REST API Consecutive Call is not working - c#

SOLVED
The problem was sending the number with double quotes like "40".
So I replaced quotes with empty space and It worked.
This is the code.
HRMID = HRMID.Replace('"', ' ').Trim();
I am trying to call my REST service consecutively but only one of them is working when I do that.
If I call only one of them in one block it works but two of them in one function block is causing problems I think,I don't know why.
Maybe it is something about restriction in the service.
There is no Error just it is not updating the Database.
If I use it alone it works so call is correct.
This is my code , I am waiting for suggestions.
Thanks!
private void GameClosed(object sender, EventArgs e)
{
// Do your stuff when the game closed.
try
{
var client = new WebClient();
var result = client.DownloadString(wsUrl + "/rest/gethrmid/" + UserValues[4]);// Only the first REST API call is working.This one works.
MessageBox.Show("Result is :" + result);
string HRMID = result;
StreamReader SR = new StreamReader("D:/HRMSession.txt");
string hrmValues = SR.ReadToEnd();
client.DownloadString(wsUrl + "/rest/inserthrmsession/" + HRMID + "/" + hrmValues);//This one is not working if i put here.
}
catch (Exception a)
{
MessageBox.Show(a.ToString());
}
}
EDIT:
If I write it as hardcoded it works but if I use the value that is coming from first call it doesn't work.
client.DownloadString(wsUrl + "/rest/inserthrmsession/" + 40 + "/" + hrmValues);//Works.
But I can not convert the value of HRMID to Int because operation contract is string...

Related

Winnovative With Parameters in URL

i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);

can't get the body/attachments of new mails in outlook

I've developed an Outlook plugin using C# where for each new mail received, i get(and save) the sender/subject/the body of email & the attachments. Well, the last 2 gave me a headache. I can see the sender and the subject of the new mail but for the body&attachments it seems that is a problem. I've used NewMailEx for getting the new mails in Inbox. The function looks like this:
private void Application_NewMailEx(string EntryIDCollection)
{
string[] entryIdArray = EntryIDCollection.Split(',');
foreach (string entryId in entryIdArray)
{
try
{
Outlook.MailItem item = (Outlook.MailItem)Application.Session.GetItemFromID(EntryIDCollection, null);
string subj = item.Subject; //works
string to = item.To; //works
string bec = item.BCC; //does not work but dont care
string body = item.Body; //DOES NOT SAVE THE BODY OF THE NEW MAIL RECEIVED
string final = "Sender: " + item.SenderEmailAddress + "\r\n" + "Subject: " + subj + "\r\n" + "BCC: " + bec + "\r\n" + "TO: " + to + "\r\n\n" + "Body: " + body + "\r\n\n";
System.IO.File.AppendAllText(#"D:\tmp\atr.txt", final);
//the result of item.attachments.count is always 0 , even though I've
//sent mails with a different number of attachments. So the if
//statement is false
if (item.Attachments.Count > 0)
{
for (int i = 1; i <= item.Attachments.Count; i++)
{
item.Attachments[i].SaveAsFile(#"D:\tmp\" + item.Attachments[i].FileName);
}
}
Marshal.ReleaseComObject(item);
}
catch (System.Exception e)
{
MessageBox.Show(e.Message);
}
}
}
Where does the Item variable come from? You need to initialize it using Application.Session.getItemfromID().
I'm writing in VBA, so I feel like posting my code here would be a faux pas, but I have come to a solution using similar Object Libraries from the Outlook application that I think transfer well to your C++ intentions.
First of all, switching to POP3 certainly fixes this problem, but you're stuck using POP3, which is only ideal from a programming standpoint.
The solution I have found follows this algorithm:
//Generate Outlook MailItem Object, "item"
//If item.DownloadState is not 1,
//item.Display
//item.Close(1)
//Perform end of code operations
//Call Function that is identical to Application_NewMailEx but is not Application_NewMailEx because Application_NewMailEx is a function that is thrown during the incoming mail event.
//Else,
//Perform Intended Code
You see how calling a function identical to Application_NewMailEx creates a kind of loop because if item.DownloadState is not 1, you'll be calling that function again? I get that this isn't the most ideal coding practice, but I have scoured the internet and Outlook Application and Outlook Object Library experts have no idea how to solve this problem any other way (in fact, no one even proposes THIS solution)
For my full VBA Solution Check out:
https://superuser.com/questions/894972/outlook-strange-item-attachments-error/990968#990968

String that came from Request.Url.ToString() misteriously changes to another string when manipulating/comparing the first characters

I'm aware that there are easier ways to do this and believe me, I've tried them. I'm of course open to any suggestions =). You don't need to read the whole code, just the part that says where the problem lies. Also, I'm debbugging perl style so you guys can see. Oh and did I mention that on my development environment everything works as intended?
Here's the code:
string GetPortalAlias()
{
String myURL2 = Request.Url.ToString();
URLLabel.Text = "Original Request.Url.ToString() returned: \"" + myURL2 + "\"";
string myURL = string.Copy(myURL2);
URLLabel.Text = "Copying it to myURL, it's now: \"" + myURL + "\"";
myURL = myURL.ToLower().Trim();
URLLabel.Text += "<br>Trimming and ToLower myURL.<br>The new url is \"" + myURL + "\"" + "<br>";
myURL = myURL.Replace(":80", "");
URLLabel.Text += "Replacing the \":80\".<br> The new url is\"" + myURL + "\"<br>";
//***HERE LIES THE PROBLEM***
myURL = myURL.Replace("http://", "");
URLLabel.Text += "Replacing the \"http://\".<br> The new url is\"" + myURL + "\"<br>";
//***PROBLEM ENDS***
myURL = myURL.Remove(myURL.IndexOf("/"));
URLLabel.Text += "Removing everything after the \"/\"." + "<br> The new url is \"" + myURL + "\"<br>";
URLLabel.Text += "<br>GetPortalAlias Returning \"" + myURL + "\"";
return myURL;
}
Believe it or not, the output produced in the webpage is this:
Copying it to myURL, it's now: "http://sar.smg.com.ar/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://sar.smg.com.ar/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
So... for some reason whenever it reaches the replace section it mysteriously mutates to start with "intranetqa" instead of "sar.smg.com.ar". "intranetqa" is our default hostname. CHANGING OR TAKING AWAY ANY CHARACTER OF HTTP:// IN ANY WAY MUTATES THE STRING.
I do a string.copy because I'm aware that if two strings are equal the compiler stores them in the same place therefore I wanted to prevent errors. Taking those lines away and use Request.Url.ToString() tomyURL directly does nothing at all. They were just a test to see if that worked.
Here's a list of the things I've tried:
All combinations of string / String, none worked.
I've tried Request.Host.Url and it just gave me "intranetqa".
I've used Request.Url.AbsoluteUri and that's why I have the replace
:80 line.
USING THE .tochararray FUNCTION GIVES ME BACK THE INTRANETQA THING
myURL = myURL.Substring(6) gives back the intranetqa thing.
string.Contains("sar.smg.com.ar") gives back false.
I believe the trick lies around here:
Uri uriAddress1 = Request.Url; and "The parts are <br>" + "Part 1: " + uriAddress1.Segments[0] + "<br>Part 2: " + uriAddress1.Segments[1]; Gives Part1 : "/" and Part 2: "Default.aspx". Trying to access part 3 (index 2) gives an exception.
The request.url does not have the first part, but when I call the ToString() method, it does have like a "fake" first part
Between your browser and the server are a reverse proxy and an output re-writer. These may be the same component, or separate components.
The URL your server actually sees is always of the form http://intranetqa/default.aspx?tabid=912 (after the reverse proxy/URL re-writer has intercepted the request).
The output your server produces is actually like:
Copying it to myURL, it's now: "http://intranetqa/Default.aspx?TabID=912"
Trimming and ToLower myURL.
The new url is "http://intranetqa/default.aspx?tabid=912"
Replacing the ":80".
The new url is"http://intranetqa/default.aspx?tabid=912"
Replacing the "http://".
The new url is"intranetqa/default.aspx?tabid=912"
Removing everything after the "/".
The new url is "intranetqa"
GetPortalAlias Returning "intranetqa"
The output re-writer is inspecting the output from your server and doing a replace of http://intranetqa with http://sar.smg.com.ar. Once you strip the http:// off of the front of these strings, it's no longer a match and so replacement no longer occurs.
If you want to know what the original requesting URL/host are, hopefully the reverse proxy either is, or can be configured to, adding an extra header to the request with the original URL.
You can try something like this
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]);
Uri.Segments Property
This is better way to handle URIs and their segments.
Try to use this property instead:
String myURL2 = Request.Url.AbsoluteUri;
Here is an Extension method that I use to pull the SiteRootPath. You should be able to easily adjust it however you need it. You will need access to the HttpContext for what I currently have below, however, you don't sound like you need that.
using System;
using System.Web;
namespace FlixPicks.Web.Extensions
{
public static class HttpContextExtensions
{
public static string SiteRootPath(this HttpContext context)
{
if (context == null || context.Request == null) { return null; }
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
public static string SiteRootPath(this HttpContextBase context)
{
return context.Request.Url.SiteRootPath(context.Request.ApplicationPath);
}
private static string SiteRootPath(this Uri url, string applicationPath)
{
if (url == null) { return null; }
// Formatting the fully qualified website url/name.
string appPath = string.Format(
"{0}://{1}{2}{3}",
url.Scheme,
url.Host,
url.Port == 80 ? string.Empty : ":" + url.Port,
applicationPath);
// Remove ending slash(es) if one or more exists to consistently return
// a path without an ending slash. Could have just as well choosen to always include an ending slash.
while (appPath.EndsWith("/") || appPath.EndsWith("\\"))
{
appPath = appPath.Substring(0, appPath.Length - 1);
}
return appPath;
}
}
}
Good luck,
Tom
Don't you want to achieve part of what is done here?
Something like
string host = Request.Url.IsDefaultPort ?
Request.Url.Host :
Request.Url.Authority;
If you want to persist with the old method change it like this
string GetPortalAlias()
{
var rawUrl = Request.Url.ToString();
var lowerTrimmedUrl = rawUrl.ToLower().Trim();
var withoutPortUrl = lowerTrimmedUrl.Replace(":80", "");
var withoutProtocolUrl = withoutPortUrl.Replace("http://", "");
var justHostUrl = withoutProtocolUrl.Remove(myURL.IndexOf("/"));
var evolution = new StringBuilder();
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(rawUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(lowerTrimmedUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutPortUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(withoutProtocolUrl));
evolution.AppendFormat(
"{0}<br>",
HttpUtility.HtmlEncode(justHostUrl));
URLLabel.Text = evolution.ToString();
return justHostUrl;
}
So you can see whats going on.

Weird Error when using SOAP Web Service

For a school project, I have to create a Java Server that is able to service a .NET client that has a Service Reference to a WSDL. I have the .NET Client code:
using (var client = new MathServiceWSDLClient())
{
Console.WriteLine("Multiplying " + Num1 + " and " + Num2 + ": " + client.Multiply(Num1, Num2));
Console.WriteLine("Adding" + Num1 + " and " + Num2 + ": " + client.Add(Num1, Num2));
}
I have also written the Java Server:
Scanner sc = new Scanner(socket.getInputStream());
boolean clientExpectContinue = false;
int contentLength = -1;
String line;
while (!(line = sc.nextLine()).isEmpty()) {
System.out.println(line);
if (line.startsWith("Content-Length")) {
String[] elements = line.split(": ");
contentLength = Integer.parseInt(elements[1]);
} else if (line.startsWith("Expect")) {
clientExpectContinue = true;
}
}
int notEmpties = 0;
byte[] soapEnvelopeData = new byte[contentLength];
char[] soapChars = new char[contentLength];
for (int i = 0; i < contentLength; i++) {
soapChars[i] = (char) socket.getInputStream().read();
if (i == 0)
System.out.println("DFSDFSDf");
}
// System.out.println(socket.getInputStream().read(soapEnvelopeData));
System.out.println(soapEnvelopeData.length);
File file = new File("tempEnvelope.txt");
FileOutputStream fileOut = new FileOutputStream(file);
// fileOut.write(soapEnvelopeData);
System.out.println("Content!");
System.out.println(new String(soapChars));
fileOut.write(new String(soapChars).getBytes());
fileOut.flush();
fileOut.close();
/* Some fancy SOAP and Reflection stuff that works */
The gist of the server is as follows:
It gets the incomming request, reads through the headers and finds the content length. It parses and saves this. From here there are two versions. The first constructs a byte array the same size as the content length, and passes the array as a parameter into the socket.getInputStream().read() method. The second constructs a char array the same length of the content and then reads individual bytes from the stream and casts them to chars.
The issue comes into play when, as shown, I attempt to run the .NET client with multiple requests in one execution. The first request goes off without any sort of discernible issue. When the second one comes in, the server reads the headers, gets the content length and constructs the array. When it comes time to read from the socket, however, the program just waits. Using the char array method, I was able to learn that it waits when reading the first value. Once one minute has expired, .NET times out, and the rest of the program breaks.
If, however, I leave the server running, and only have one request per execution of the .NET client, everything is just fine; the response comes back just as it should.
I have tried some solutions already:
Creating a new MathServiceWSDLClient for every request
Putting every request in its own using() block.
Doing two of the same request at once: two Multiply() or Add() requests.
Any help is appreciated. Thank you all in advance.
~Ryno Janse van Rensburg
.net is probably keeping the socket open for subsequent requests. There may be a bug in your server-like java code related to this.
Are you able to use a framework instead for the Java server code? I would strongly recommend this, and recommend rmbedded Jetty without hesitation. This would mean you wouldn't have to work at the socket level in Java - you can let Jetty handle all of that complication.

JavaScript call to page method: error 500. JSON

I'm using the auto complete control here:http://www.ramirezcobos.com/labs/autocomplete-for-jquery-js/comment-page-2/
And i've modified it as:
var json_options;
json_options = {
script:'ReportSearch.aspx/GetUserList?json=true&limit=6&',
varname:'input',
json:true,
shownoresults:true,
maxresults:16,
callback: function (obj) { $('#json_info').html('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')'); }
};
$('#ctl00_contentModule_txtJQuerySearch').autoComplete(json_options);
I have the following method in C# Code behind (aspx.cs)
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetUserList(string input)
{
List<string> lUsers = new List<string>();
Server.DAL.SQLServer2005.User user = new Server.DAL.SQLServer2005.User();
Server.Info.AuthUser aUser = (Server.Info.AuthUser)HttpContext.Current.Session["AuthUser"];
List<Server.Info.User.UserDetails> users = user.GetUserList(aUser, input, 16, true);
users.ForEach(delegate(ReportBeam.Server.Info.User.UserDetails u)
{
lUsers.Add("(" + u.UserName + ")" + u.LastName + ", " + u.FirstName);
});
return lUsers.ToArray();
}
The error I get back is:
Server Error in '/WebPortal4' Application. Unknown web method
GetUserList. Parameter name: methodName
If I change any of the paraemeter names I get an error telling me the paremeter names are not in match. now that everything is as it should, it's bombing.
Any help would rock.
If your code is in a user control, (and not in the actual aspx), that might cause problems. I guess it shouldn't, but I've had problems with it myself, don't remember exactly how they looked, but in the end I retorted to placing my web methods in asmx files instead of aspx files, if they are to be reached from anything but the aspx itself, and it's been working out great =)

Categories