UnityWebRequest not calling server - networking

I have code to use UnityWebRequest to call a webserver. Debugging it revealed that it never even calls the server and always returns with 0 bytes. I have attached a debugger to my server and can see that it does not get called.
Even tried calling google and still have an empty result. These tests were done from within the unity editor.
Is there something I need to enable before I can use networking libraries?
void Awake() {
StartCoroutine("CallWebserverCR");
}
IEnumerator CallWebserverCR()
{
UnityWebRequest www = UnityWebRequest.Get("http://www.google.com");
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
byte[] results = www.downloadHandler.data;
}
}

Only difference I see between your code and Unity's example is that they have a 'using' statement:
IEnumerator GetText() {
using(UnityWebRequest www = UnityWebRequest.Get("http://www.my-server.com")) {
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
}

Related

ASP.NET Entity Framework return JSON object of all rows inside table

I am trying to return JSON object from PostgreSQL db and currently saving to database works fine, but trying to return result returns nothing this is currently what I have for returning list from db. Keep in mind connection string is fine functionality for creating object to db works fine.
public async Task<IEnumerable<TutorialMake>> ReadTutorialMake()
{
try
{
using (var db = new TutorialContext())
{
response = HttpStatusCode.OK;
return db.TutorialMakes.ToList();
}
} catch
{
response = HttpStatusCode.BadRequest;
return null;
}
}
I've tried with returning only db.TutorialMakes without enumerable still nothings, removing try and catch returns no errors, iqueryable returns nothing and there is data inside table
Code is fine, it was just the way I configured my API I didn't return the list in API.
Because you forget to convert List result to JsonObject
Example :
public async Task<JsonResult> ReadTutorialMake()
{
try
{
using (var db = new TutorialContext())
{
response = HttpStatusCode.OK;
return Json(db.TutorialMakes.ToList()); //Convert result to JsonResult
}
} catch
{
response = HttpStatusCode.BadRequest;
return null;
}
}

Unable to Access SQLite Data in MvvmCross ViewModel

Hello StackOverflow community,
I know there's a lot of code in this post, but I wanted to give you guys, the community as good of a picture as possible as to what is going on here so that maybe someone can help me figure out what my issue is.
Recently for a project I'm working on we've decided to upgrade from MvvmCross 5.7.0 to 6.2.2. I've managed to get our UWP app to successfully complete the initialization and setup process. The first viewmodel for which we register the app start also starts initializing. However, I'm finding that my vm initialization hangs at a particular line of code (shown in the code below). The weirdest part though is similar methods called in the app initialization code run perfectly fine without hanging/deadlock, so I'm not sure what's different Here's a simplified version of my viewmodel code to illustrate:
public class MyViewModel : BaseAuthenticatedTabBarViewModel, IMvxViewModel<int>
{
private int? _settingValue;
public override async Task Initialize()
{
//Some irrelevant initialization code
Exception e = null;
try
{
//This line of code never returns
_settingValue = _settingValue ?? await AppSettingService.GetSettingValue();
}
catch (Exception ex)
{
e = ex;
}
if (e != null)
{
await HandleCatastrophicError(e);
}
}
}
The AppSettingService.GetSettingValue() method looks like this:
public async Task<int?> GetCurrentEventId()
{
return await GetNullableIntSetting("SettingValue");
}
private static async Task<int?> GetNullableIntSetting(string key)
{
try
{
var setting = await SettingDataService.SettingByName(key);
if (setting != null)
{
return string.IsNullOrEmpty(setting.Value) ? (int?)null : Convert.ToInt32(setting.Value);
}
}
catch (Exception ex)
{
//Handle the exception
}
return null;
}
All the code for SettingDataService:
public class SettingDataService : DataService<SettingDataModel>, ISettingDataService
{
public async Task<SettingDataModel> SettingByName(string name)
{
try
{
var values = (await WhereAsync(e => e.Name == name));
return values.FirstOrDefault();
}
catch(Exception ex)
{
//Handle the exception
}
return null;
}
}
Finally, the implementation for WhereAsync() is in a class called DataService and is as follows:
public virtual async Task<IEnumerable<T>> WhereAsync(System.Linq.Expressions.Expression<Func<T, bool>> condition, SQLiteAsyncConnection connection = null)
{
return await (connection ?? await GetConnectionAsync())
.Table<T>()
.Where(condition)
.ToListAsync();
}
Thank you very much for your help in advance
Edit: Forgot to also add this crucial bit of code to help you guys even further:
protected async Task<SQLiteAsyncConnection> GetConnectionAsync()
{
SQLiteAsyncConnection connection = null;
while (true)
{
try
{
connection = Factory.Create(App.DatabaseName);
// This line of code is the culprit. For some reason this hangs and I can't figure out why.
await connection.CreateTableAsync<T>();
break;
}
catch (SQLiteException ex)
{
if (ex.Result != Result.CannotOpen && ex.Result != Result.Busy && ex.Result != Result.Locked)
{
throw;
}
}
await Task.Delay(20);
}
return connection;
}
I'm suspecting that you are calling Task.Wait or Task<T>.Result somewhere further up your call stack. Or if you're not doing it, MvvmCross is probably doing it for you. This will cause a deadlock when called from a UI context.
Personally, I prefer the approach that ViewModels should always be constructed synchronously, and cannot have an asynchronous "initialization". That is, they must construct themselves (synchronously) into a "loading" state, and this construction can kick off an asynchronous operation that will later update them into a "loaded" state. The synchronous-initialization pattern means there's never an unnecessary delay when changing views; your users may only see a spinner or a loading message, but at least they'll see something. See my article on async MVVM data binding for a pattern that helps with this, and note that there's a newer version of the helper types in that article.

#Url.Content doesnt resolve absolute path on one server but does on another

We currently have two different servers on same domain. But one server resolves
#Url.Content("~/api/User")'
as
http://domain.com/virtualdirectory/api/User
where as other server doesnt resolve it absolutely; rather it resolves it relatively like
api/user
The code base is same and we are using MVC4. I am not sure as to where we went wrong or if there is any IIS/DNS settings that need to be done in order to get this fixed.
All help is appreciated; thanks :)
This is related with the IIS Rewriting module in your IIS web server that return the path to http://domain.com/virtualdirectory/api/User
Take a look on the part of source code of #Url.Content below:
private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath)
{
if (String.IsNullOrEmpty(contentPath))
{
return contentPath;
}
// can't call VirtualPathUtility.IsAppRelative since it throws on some inputs
bool isAppRelative = contentPath[0] == '~';
if (isAppRelative)
{
string absoluteContentPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);
return GenerateClientUrlInternal(httpContext, absoluteContentPath);
}
// we only want to manipulate the path if URL rewriting is active for this request, else we risk breaking the generated URL
bool wasRequestRewritten = _urlRewriterHelper.WasRequestRewritten(httpContext);
if (!wasRequestRewritten)
{
return contentPath;
}
// Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base
// of our absolute paths. For example, consider mysite.example.com/foo, which is internally
// rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to
// base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar,
// which is incorrect.
string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath);
string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination);
return absoluteUrlToDestination;
}
Use the codes below to check whether your web servers are having the URL rewritten:
bool requestWasRewritten = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable("IIS_WasUrlRewritten") != null);
And Also:
private volatile bool _urlRewriterIsTurnedOnCalculated = false;
private bool _urlRewriterIsTurnedOnValue;
private object _lockObject = new object();
private bool IsUrlRewriterTurnedOn(HttpContextBase httpContext)
{
// Need to do double-check locking because a single instance of this class is shared in the entire app domain (see PathHelpers)
if (!_urlRewriterIsTurnedOnCalculated)
{
lock (_lockObject)
{
if (!_urlRewriterIsTurnedOnCalculated)
{
HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));
//bool urlRewriterIsEnabled = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlRewriterEnabledServerVar) != null);
bool urlRewriterIsEnabled = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable("IIS_UrlRewriteModule") != null);
_urlRewriterIsTurnedOnValue = urlRewriterIsEnabled;
_urlRewriterIsTurnedOnCalculated = true;
}
}
}
return _urlRewriterIsTurnedOnValue;
}
In summary, If both requestWasRewritten and IsUrlRewriterTurnedOn
return true, that means one of your web server has IIS Rewrite Module
turned on and running while the other one doesn't have.
For more details on ASP.NET MVC source codes, please refer to this link:
http://aspnetwebstack.codeplex.com/
Hope it helps!

Remote Shared Object comes undefined - Red5

Cant find any solution for this. Im trying to store some data on remote shared object and retrieve it. At the moment im working locally. Anyway, i read probably all posts on internet about that and still cant understand where is my problem. I managed to store arguments on rso, but when i tried to receive those values, im only getting undefined.
Here is my code for the version when im only working with client side and on server side just watching when client connects to shared objects or changes the value.
protected function application1_creationCompleteHandler(event:FlexEvent):void {
var room_id:Number = vars("room");
connection = new NetConnection();
connection.connect("rtmp://127.0.0.1/video/" + room_id);
connection.addEventListener(NetStatusEvent.NET_STATUS, onConnected);
connection.client = this;
}
private function onConnected(event:NetStatusEvent) : void {
if(event.info.code == "NetConnection.Connect.Success") {
so = SharedObject.getRemote("video", connection.uri, true);
so.addEventListener(SyncEvent.SYNC, onSync);
so.connect(connection);
// if i try to trace so in there it will be undefined
} else {
Alert.show("Unsuccessful Connection", "Information");
}
And finally:
private function onSync(event:SyncEvent):void {
for(var i:Object in event.changeList) {
var changeObj:Object = event.changeList[i];
switch(changeObj.code) {
case "success":
if(so.data.cameras) {
Alert.show(this.so.data.cameras.toString(), "I changed it");
} else {
Alert.show("I changed", "Information");
}
break;
case "change":
if(so.data.cameras)
Alert.show(so.data.cameras.toString(), "First");
else if (this.so.data.cameras) {
Alert.show(this.so.data.cameras.toString(), "Second");
} else {
Alert.show("Can't found changed value", "Error");
}
break;
}
}
}
And here we go, i always get the undefined value of cameras, unless im the client who is changing the value, but everybody else gets undefined value. So i cant understand, all listeners a noticed about changes, on the server side code i see that i have changes, and i even opened persistent red5 shared object file and i see there is value, but i just cant retrieve it. Anybody has a solution? I would be very grateful.
Updated:
Answer is here: rso between flex and red5. I can create but cant read

Check if user exists in Active Directory

I need to check if an user exists in AD and if so, retrieve some user information. I have been able to do this as shown below. But, it is very slow. Is there any way to do this faster?
Thanks!
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
Console.WriteLine("Enter AD account name...");
string strADLoginName = Console.ReadLine();
using(PrincipalContext context = new PrincipalContext(ContextType.Domain,"DEVMC"))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, strADLoginName))
{
bool userExists = (user != null);
if (userExists)
{
Console.WriteLine("User exists");
Console.WriteLine(user.EmailAddress);
}
else
{
Console.WriteLine("User doesn't exist");
}
}
}
Console.ReadKey();
}
}
}
Well, the only real approach you could tak to make this faster would be to have the "PrincipalContext" be constructed once somewhere and cached for future use, so you don't have to re-create that context over and over again, every time you call that function.
Other than that - no, I don't see much room for improvement right here and now. What kind of app is this?? ASP.NET web apps, or Winforms, WPF, Silverlight??

Resources