web service is not working on server side - c#

i have created a we bservice named test.asmx which looks like this:
[WebService(Namespace = "http://insforia.com/Webservices/StockTickers/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod(Description = "Using stock symbol gets delayed stock information from Yahoo.", EnableSession = false)]
public string[] GetQuote()
{
string username = Session["username"].ToString();
string company = "BSE-100.BO+COALINDIA.BO+TCS.BO+WIPRO.BO+SBIN.NS+MNM.BO+RCOM.BO+TATASTL.BO+GMRINFRA.BO+ICICIBANK.BO";
string stockcodes = "sl1c6";
string url = "http://in.finance.yahoo.com/d/quotes.csv?s=" + company + "&f=" + stockcodes;
var webRequest = HttpWebRequest.Create(url);
var webResponse = webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
buffer = sr.ReadToEnd();
}
var buffer = buffer.Replace("\"", "");
buffer = buffer.Replace("\r\n", ",");
var bufferList = buffer.Split(new char[] { ',' });
return bufferList;
}
and i am calling this web service in my aspx page like this:
private string userid = "admin";
protected void Page_Load(object sender, EventArgs e)
{
Session["username"] = userid;
test oo = new test();
bufferList = oo.GetQuote();
}
the thing is its working perfectly in my localhost but when i uploaded it on server its giving me an error that it couldn't find the test
to see the exact error this is the link :
http://insforia.com/Webservices/StockTickers/stockmain.aspx
i don't understand what to do? why this is happening. i know this is a very stupid question to ask here but i am trying this from yesterday.

try to dont use session.
send param for userName;
public string[] GetQuote(string UserName)
{
...
return bufferList;
}

Related

Retrieving data from an API

The first part of the program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered. (Which I have done)
The second part, the user will enter a specific "to" and "from" date.
Using the signature obtained from the first part and the dates that the user enters, the program should pass this information to an API address and obtain information accordingly.
My question is that I am not sure how to pass the obtained signature to the new API address + the "to" and "from" date.
The first part of the program to retrieve the signature (works perfectly):
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
The second part that I have written so far:
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = StaticStrings.UrlNcert + username + "&fromDate=" + fromDate + "&toDate=" + toDate;
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
}
The API strings:
namespace TimeSheets_Try_11.Controllers
{
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT" + #"\";
}
}
For example if we are using the name "Jane Dow" from the date 9/22/20 - 9/29/20, the api strings will be
UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/Jane
UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT\JDOW&fromDate=2020-09-22&toDate=2020-09-29"
Trivial way - change UrlNcert to url without query at first:
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost";
}
Then in your api call get values for username, fromDate and toDate and use string interpolation.
var url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
If you want more complex way, check UriBuilder

No connection could be made because the target machine actively refused it 129.172.174.102:50491

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?

.NET Core 2.0 Is the below code thread safe

Here's my code and I have doubt on thread safe implementation. My questions are below
The return value from GetHtmlPageAsync is object. Is it thread safe? I will use this object and add into the collection and finally upload into database.
The main method logic is below (implementation in-progress). I have set of domains, I have list of 10000 domains in the collection, the idea is, I will put it in the queue and call the GetHtmlPageAsync to get the HTML of the page. Based on the HTML, I will get the necessary hyperlinks. Once I get the hyper links, I will check certain word is available in the link. If the word is available in the link, I will call the same method GetHTMLPageAsync to get the HTML of that page. So the same thread may call the GetHtmlPageAsync to process another link. I am trying to reuse the same method for multiple calls in thread safe way. Please help.
#edit1 . I have added the main method. Instead of Queue. I have used ForEach
public static async Task<int> ProcessDomainAsync(List<string> domains)
{
Parallel.ForEach(domains, async (currentDomain) =>
{
var domainBody = await GetHtmlPageAsync(currentDomain);
var language = string.Empty;
var country = string.Empty;
var createdOn = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
var updatedOn = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
var machine = Environment.MachineName;
var message = "[" + domainBody.ErrorCode + "] - " + domainBody.ErrorMessage;
var active = false;
var stage = "End";
var url = currentDomain;
if (domainBody.ErrorCode == 0)
{
var html = domainBody.Body;
language = Common.GetLanguageIdentification(html);
country = Common.GetCountryIdentification(currentDomain);
message = string.Empty;
active = true;
stage = "Stage1";
var hyperLinks = Common.GetAllAHrefTags(html);
//Process Hyper Links
}
_domainList.Add(new Domain
{
Url = url,
Language = language,
Country = country,
MachineName = machine,
Message = message,
Active = active,
Stage = stage,
CreatedOn = createdOn,
UpdatedOn = updatedOn
});
domainCount++;
});
return domainCount;
}
public class DomainBody
{
public string Body;
public string ErrorMessage;
public int ErrorCode;
}
public static class DomainProcessing {
static async Task<DomainBody> GetHtmlPageAsync(string url)
{
#region Initialize Proxy
var sessionId = new Random().Next().ToString();
var proxy = new WebProxy(Constant.ProxyUrl, Constant.ProxyPort);
var login = Constant.ProxyUserName + "-session-" + sessionId;
proxy.Credentials = new NetworkCredential(login,Constant.ProxyPassword);
#endregion
#region Initialize Variables
var user_agent = Common.GenerateRandomUserAgent();
var body = string.Empty;
var errorCode = 0;
var errorMessage = string.Empty;
#endregion
try
{
#region Format URL with Http Protocol
var domainSB = new StringBuilder();
domainSB.Append("http://");
domainSB.Append(url);
#endregion
#region Process Domain
var request = (HttpWebRequest) WebRequest.Create(new Uri(url));
request.Proxy = proxy;
request.UserAgent = user_agent;
request.Timeout = Constant.TimeOut;
using (var response = await request.GetResponseAsync().ConfigureAwait(true))
using (var content = new MemoryStream())
using (var responseStream = response.GetResponseStream())
{
await responseStream.CopyToAsync(content);
var bodyArray = content.ToArray();
body = Encoding.UTF8.GetString(bodyArray, 0, bodyArray.Length);
}
errorCode = 0;
errorMessage = string.Empty;
#endregion
}
catch (HttpRequestException ex)
{
body = string.Empty;
errorCode = ex.InnerException.HResult;
errorMessage = ex.InnerException.Message;
}
catch (Exception ex)
{
body = string.Empty;
errorCode = ex.HResult;
errorMessage = ex.Message;
}
var domainBody = new DomainBody
{
Body = body,
ErrorCode = errorCode,
ErrorMessage = errorMessage
};
return domainBody;
}
}enter code here
Generally speaking, local variables should be thread safe (simply because they have no idea there even is another thread and other threads have no way to access them).
Anything that can be accessed by multiple threads should be looked at. _domainList for example. Make sure the Add method is thread-safe because you are calling it potentially in parallel.

RallyAPI - Change TestCase owner via API

I have the user object from the GetCurrentUser() call, and I have the Test Case as a DynamicJsonObject, but simply setting the TestCase["Owner"] to the current user doesn't work - anybody got a code sample where this works?
GAAH! I was so close, that I stumbled on the answer:
DynamicJsonObject owner = new DynamicJsonObject();
owner["Owner"] = restApi.GetCurrentUser()["_ref"].ToString();
restApi.Update(existingTestCase["_ref"], owner);
Works perfectly - thanks for the help.
Owner attribute is a reference to a User object. Here is a Java example when a test case is created and the owner is set:
public class CreateTCsetOwner {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String wsapiVersion = "v2.0";
String projectRef = "/project/222";
String workspaceRef = "/workspace/111";
String applicationName = "RestExample_createTCsetOwner";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserName", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "otheruser#co.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
String userRef = "";
for (int i=0; i<userQueryResponse.getResults().size();i++){
JsonObject userJsonObject = userQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("UserName: " + userJsonObject.get("UserName"));
userRef = userJsonObject.get("_ref").getAsString();
}
try {
for (int i=0; i<1; i++) {
System.out.println("Creating a test case...");
JsonObject newTC = new JsonObject();
newTC.addProperty("Name", "some test");
newTC.addProperty("Owner", userRef);
CreateRequest createRequest = new CreateRequest("testcase", newTC);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read TC
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading testcase %s...", ref));
GetRequest getRequest = new GetRequest(ref);
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a testcase: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}

Adding Facebook log in button - can't retrieve email address on server side

I am trying to add a simple log in with Facebook button to my ASP.NET (C#) website. All I need is on the server side to retrieve the Facebook user's email address once they have logged in.
I was trying to use this example but it seems that the cookie "fbs_appid" is no longer used and instead there is one called "fbsr_appid".
How can I change the sample to use the different cookie? Alternately does anyone have a working example of retrieving the logged in Facebook user's email address.
I know there is an SDK I can use but I want to keep things simple. The above example would be perfect if it worked.
I managed to get the information needed using the fbsr cookie. I created the following class which does all of the work to confirm the user logged in with Facebook and then retrieves the user's details:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
namespace HarlequinShared
{
public class FacebookLogin
{
protected static string _appId = null;
protected static string AppId
{
get
{
if (_appId == null)
_appId = ConfigurationManager.AppSettings["FacebookAppId"] ?? null;
return _appId;
}
}
protected static string _appSecret = null;
protected static string AppSecret
{
get
{
if (_appSecret == null)
_appSecret = ConfigurationManager.AppSettings["FacebookAppSecret"] ?? null;
return _appSecret;
}
}
public static FacebookUser CheckLogin()
{
string fbsr = HttpContext.Current.Request.Cookies["fbsr_" + AppId].Value;
int separator = fbsr.IndexOf(".");
if (separator == -1)
{
return null;
}
string encodedSig = fbsr.Substring(0, separator);
string payload = fbsr.Substring(separator + 1);
string sig = Base64Decode(encodedSig);
var serializer = new JavaScriptSerializer();
Dictionary<string, string> data = serializer.Deserialize<Dictionary<string, string>>(Base64Decode(payload));
if (data["algorithm"].ToUpper() != "HMAC-SHA256")
{
return null;
}
HMACSHA256 crypt = new HMACSHA256(Encoding.ASCII.GetBytes(AppSecret));
crypt.ComputeHash(Encoding.UTF8.GetBytes(payload));
string expectedSig = Encoding.UTF8.GetString(crypt.Hash);
if (sig != expectedSig)
{
return null;
}
string accessTokenResponse = FileGetContents("https://graph.facebook.com/oauth/access_token?client_id=" + AppId + "&redirect_uri=&client_secret=" + AppSecret + "&code=" + data["code"]);
NameValueCollection options = HttpUtility.ParseQueryString(accessTokenResponse);
string userResponse = FileGetContents("https://graph.facebook.com/me?access_token=" + options["access_token"]);
userResponse = Regex.Replace(userResponse, #"\\u([\dA-Fa-f]{4})", v => ((char)Convert.ToInt32(v.Groups[1].Value, 16)).ToString());
FacebookUser user = new FacebookUser();
Regex getValues = new Regex("(?<=\"email\":\")(.+?)(?=\")");
Match infoMatch = getValues.Match(userResponse);
user.Email = infoMatch.Value;
getValues = new Regex("(?<=\"first_name\":\")(.+?)(?=\")");
infoMatch = getValues.Match(userResponse);
user.FirstName = infoMatch.Value;
getValues = new Regex("(?<=\"last_name\":\")(.+?)(?=\")");
infoMatch = getValues.Match(userResponse);
user.LastName = infoMatch.Value;
return user;
}
protected static string FileGetContents(string url)
{
string result;
WebResponse response;
WebRequest request = HttpWebRequest.Create(url);
response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
protected static string Base64Decode(string input)
{
UTF8Encoding encoding = new UTF8Encoding();
string encoded = input.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var decoded = Convert.FromBase64String(encoded.PadRight(encoded.Length + (4 - encoded.Length % 4) % 4, '='));
var result = encoding.GetString(decoded);
return result;
}
}
public class FacebookUser
{
public string UID { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
And then I can use this in my login page:
FacebookUser user = FacebookLogin.CheckLogin();
if (user != null)
{
Response.Write("<p>" + user.Email);
Response.Write("<p>" + user.FirstName);
Response.Write("<p>" + user.LastName);
}
This is further explained here.
I believe that this method is secure and does the job as simply as possible. Please comment if there is any concerns.
This is not at all how you should be doing things, especially if you are trying to do it on the server side. You should not use the cookie.
The different sdks make things simpler, they (especially the official ones) stay up to date with facebook changes, unlike the example you provided that just stopped working when the cookie name was changed.
I'm not a C# developer, and never tried to use facebook from that environment so I can't tell you exactly how to do it with C#, but this is the main concept:
When you send the user for authentication (assumed Server Side Flow) you need to ask the user for permissions for anything but basic and public user information.
The email field is filed under "extended permission" and you need to ask for it specifically, something like this:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_url=YOUR_REDIRECT_URI&scope=email
(You can read more about permissions here)
Once the user authorized your app and granted you with the permissions, you can then ask for that data.
You can do it in the server side by asking for the "/me" graph path (or just the email: "me?fields=email").
You can also do it in the client side with the javascript sdk:
FB.api("/me", function(response) {
console.log(response);
});

Categories

Resources