client send json and retrieve it in server - web-services

Now I'm bulding game by UNITY3D. I want to send json file to server to store it in database I build server by php with Yii Framework, i have problem with send data in client [UNITY3D] and retrieve it in server [Yii]. Please help me.UNITY3D code: I want to send 'name' -> to server
var url = "http://localhost:8888/TPP/index.php/site/saveName";
var form = new WWWForm();
form.AddField( "player", "Henry" );
var download = new WWW( url, form );
print(download);
yield download;
if(download.error) {
print( "Error downloading: " + download.error );
return;
} else {
// show the highscores
Debug.Log(download.text);
}
In Yii, i tried to get data in request
public function actionSaveName() {
if(isset($_POST['name']) {
echo $_POST['name'];
} else {
echo "nothing";
}
}
Is that right?

The unity part is fine, but in yii you'll have to check for $_POST['player'] instead of $_POST['name'] because according to the AddField() documentation, the first parameter is the name of the generated form element.
If you want to have it as name then you'll have to change AddField as : form.AddField("name", "Henry");

Related

POST failed via Postman API to Laravel migrations database

GET is working, but POST does not. This is because it fails via Postman API to the Laravel migrations database.
function add_user(Request $request)
{
$user = new user_a;
csrf_token();
$user->user_name = $request->user_name;
$user->password = $request->password;
$res = $user->save;
if ($res) {
return ["operationn" => "Done"];
} else {
return ["operation" => "failed_404"];
}
}
in API file:
Route::post('registeruser',[dynamic_small_controller::class,'add_user']);
You are trying to send the password in integer format so it is not accepting try with giving password also in ""
{
"user_name":"yahay",
"password":"8888"
}

ASP.Net Core XUnit Integration Testing when Two Factor Authenication is enabled

I've developing an Angular web application using ASP.Net Core 3.1 for the API.
So far, I've written some integration unit tests using a Custom WebApplicationFactory to create the test server.
All tests use the HttpClient to make GETs and POSTs to the API running under the Custom WebApplicationFactory. Most of these tests initially perform a login to obtain a token to use for subsequent requests.
I'd like to add Two Factor Authentication to the application, but this will inevitably break any tests, as they aren't able to get hold of the six digit code which would be sent via email.
Here is what a test currently looks like, without MFA being implemented.
Is there a way that the test can be given the MFA code so that it can continue to perform tests?
Do I simply need to seed a user that does not have MFA enabled?
I actually want all users to have MFA enabled in production.
Many thanks
using Xunit;
using System.Threading.Tasks;
using MyCompany.ViewModels.Authentication;
using MyCompany.StaffPortal.Tests.Shared;
using StaffPortal;
using Newtonsoft.Json;
using MyCompany.ServiceA.ViewModels;
using System.Collections.Generic;
using System.Net.Http;
namespace MyCompany.Tests.StaffPortal.ServiceA
{
public class ExtensionsControllerTests : TestBase
{
public ExtensionsControllerTests(CustomWebApplicationFactory<Startup> factory) : base(factory)
{
}
[Fact]
public async Task Test_GetExtensions()
{
//This line creates a new "web browser" and uses the login details provided to obtain and set up the token so that we can request information about an account.
HttpClient httpClient = await CreateAuthenticatedHttpClient("abcltd1#MyCompany.com", "test", 1);
//Perform any work and get the information from the API
//Contact the API using the token so check that it works
var getExtensionsResponse = await httpClient.GetAsync("/api/ServiceA/extensions/GetExtensions");
//Check that the response was OK
Assert.True(getExtensionsResponse.StatusCode == System.Net.HttpStatusCode.OK, "GetExtensions did not return an OK result.");
//Get and Convert the Content we received into a List of ServiceAExtensionViewModel, as that is what GetExtensions sends back to the browser.
var getExtensionsResponseContent = await getExtensionsResponse.Content.ReadAsStringAsync();
List<ServiceAExtensionViewModel> extensionList = JsonConvert.DeserializeObject<List<ServiceAExtensionViewModel>>(getExtensionsResponseContent);
//Check the information received matches our expectations
Assert.True(extensionList.Count == 2);
Assert.True(extensionList[0].PropertyA == 123);
Assert.True(extensionList[0].PropertyB == 0161);
Assert.True(extensionList[0].PropertyC == true);
}
}
}
Here is the content's of CreateAuthenticatedHttpClient() for reference.
protected async Task<HttpClient> CreateAuthenticatedHttpClient(string username, string password, int companyAccountId)
{
var httpClient = _factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
//Create the Login information to send to the server
var loginInformation = new LoginRequestModel
{
Username = username,
Password = password,
ReturnUrl = ""
};
//Convert it into Json which the server will understand
var validLoginRequestJson = ConvertToJson(loginInformation);
//Send the Json Login information to the server, and put the response we receive into loginResponse
//In the code below, httpClient is like a web browser. You give it the
var loginResponse = await httpClient.PostAsync("/api/authenticate", validLoginRequestJson);
//Check the loginResponse was a CREATED response, which means that the token was made
Assert.True(loginResponse.StatusCode == System.Net.HttpStatusCode.Created, "New Token was not returned.");
//Check the response is identified as being in Json format
Assert.Equal("application/json; charset=utf-8", loginResponse.Content.Headers.ContentType.ToString());
//Next we have to convert the received Json information into whatever we are expecting.
//In this case, we are expecting a AuthenticationResponseViewModel (because that's what the API sends back to the person trying to log in)
//First we get hold of the Content (which is in Json format)
var responseJsonString = await loginResponse.Content.ReadAsStringAsync();
//Second we convert the Json back into a real AuthenticationResponseViewModel
AuthenticationResponseViewModel authenticationResponseViewModel = JsonConvert.DeserializeObject<AuthenticationResponseViewModel>(responseJsonString);
//Now we take the Token from AuthenticationResponseViewModel, and add it into the httpClient so that we can check the Token works.
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResponseViewModel.token);
httpClient.DefaultRequestHeaders.Add("CompanyId", companyAccountId.ToString());
return httpClient;
}

Data pass using POST method - WebRequest object

I want to use POST method to pass data over web server. I want to retrieve data provided by web server in JSON format. I have used following code by referring Unity Manual.
void Start ()
{
StartCoroutine (LoadLoginInfo ());
}
IEnumerator LoadLoginInfo ()
{
Debug.Log("Load Login Info");
WWWForm form = new WWWForm ();
form.AddField ("username", "admin");
form.AddField ("password", "Admin123#");
UnityWebRequest www = UnityWebRequest.Post (url, form);
yield return www.Send();
if (www.isError) {
Debug.Log (www.error);
} else {
Debug.Log ("Data: " + www.downloadHandler.text);
}
}
But after certain amount of wait, I am getting following message in console.
If I try similar thing in browser then it works perfectly.
So what is the correct way to use POST method using WebRequest object?

Phantomjs cookie authentication failed to capture and print the web page

I am using phantomjs to print the webpage and create a pdf. As the UI needs the user's authentication before finding the data, I used persistent cookies to authenticate the user. But somehow I got login screen every time in the created PDF. I observed that the user authenticated successfully and also the result's webpage showing proper result (debug logs showing the proper data array) but while printing the web page or creating a PDF, it somehow gets the login screen. Sometimes I observed that I got two different cookies in my PHP code while getting the report data and in javascript 'document.cookies'.
Please let me know how can I fix this.
var page = require('webpage').create(),
system = require('system'), t, address;
page.settings.userName = 'myusername';
page.settings.password = 'mypassword';
if (system.args.length === 1) {
console.log('Usage: scrape.js ');
phantom.exit();
} else {
t = Date.now();
address = system.args[1];
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
t = Date.now() - t;
var title = page.evaluate(function() { return document.title;})
console.log('Page title is ' + title);
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
});
}
Another piece of code of sending a cookie file
bin/phantomjs --cookies-file=/tmp/cookies.txt --disk-cache=yes --ignore-ssl-errors=yes /phantomjs/pdf.js 'username' 'params' '/tmp/phantomjs_file' /tmp/phantom_pdf.pdf
And
phantomjs --cookies-file=cookies.txt examples/rasterize.js localhost:7000/reports /tmp/report.pdf

Send a push notification from a windows phone device to webservice

I have a question about the push notification service of the Windows Phone 7 device:
I can now send a push notification, using a web application to a phone, changing the data of the tile. But the problem is: when I start the app, I need to display the URI in the debugger output, and then copy-paste it inside the web application, which in turn will contact the MPNS, which is fine for an update, once to a single phone. But I want to create a webservice that can make multiple calls automatically, retrieve the URI of the application ( which changes after closing-and-opening the app, I think ) and send a push notification to it. But I haven't found an MSDN - topic that deals with this. They just use commends, saying : "to be replaced later with the URI needed." So my question is: how do I use the phone to send such a message to the webservice, respond to it, and connect to the phone again, handling such request?
and also: do I need an authenticated webservice, or is there a debug version?
This is what I have thus far :
/// <summary>
/// Setup a connection with a webservice, in order to update a shell, either a toast- or a tile shell.
/// </summary>
/// <param name="shellType">The type of shell you wish to update</param>
public void SetupShellChannel ( ShellBindType shellType )
{
//holds the push notification that is created. Since we can only have one notification channel open at any one time,
//we will need to check for existance. That is why, the channelName shouldn't be changed
HttpNotificationChannel _httpChannel = HttpNotificationChannel.Find( _channelName );
//if the _httpChannel was not found ( read: does not exist )
if ( _httpChannel == null )
{
_httpChannel = new HttpNotificationChannel( _channelName );
_httpChannel.Open( );
//because there is more than one shelltype we can open, we will use a switch to call the method we seek
BindToShell( _httpChannel, shellType );
}
//Only one push notification service is allowed per application, so we cannot send a tile notification, as well as
//a toast message notification. When we attempt this, we get a InvalidOperationException
else
{
//in this case, the _httpChannel did already exist, but the problem is, we cannot just add the eventHandlers,
//because there is the danger that it didn't exist, and we would get a null pointer exception.
//_httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>( httpChannel_ChannelUriUpdated );
//_httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>( httpChannel_ErrorOccurred );
//For testing purposes, we now display the URI to the user, and as output. Normally, we would pass this URI back to the webserver
System.Diagnostics.Debug.WriteLine( _httpChannel.ChannelUri.ToString( ) );
}
//if ( _httpChannel.ChannelUri )
//When the URI is updated, we want this to be sent to the server as well, so we know that the adress has changed,
//and don't just send data somewhere into the void. Also, when encountering an error, we want to show the user when
//an error has occured.
_httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>( HttpChannel_ChannelUriUpdated );
_httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>( HttpChannel_ErrorOccurred );
}
//here, also we would return the URI to the server, but for debugging purposes, we display them to the user.
void HttpChannel_ChannelUriUpdated( object sender, NotificationChannelUriEventArgs e )
{
Deployment.Current.Dispatcher.BeginInvoke( ( ) =>
{
System.Diagnostics.Debug.WriteLine( e.ChannelUri.ToString( ) );
MessageBox.Show( String.Format( "the URI is {0}", e.ChannelUri.ToString( ) ) );
} );
}
private void BindToShell( HttpNotificationChannel channel, ShellBindType shellType )
{
switch ( shellType )
{
case ShellBindType.BindToShellTile:
channel.BindToShellTile( );
break;
case ShellBindType.BindToShellToast:
channel.BindToShellToast( );
break;
}
}
void HttpChannel_ErrorOccurred( object sender, NotificationChannelErrorEventArgs e )
{
//getting an error would be caugth here, and then displayed to the user.
Deployment.Current.Dispatcher.BeginInvoke( ( ) =>
{
MessageBox.Show( String.Format( "A push notification {0} error occured. {1}{(2)}{3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData ) );
} );
}
Ok I understand your question. What I have done is once I get teh URI from MPNS, I call a web method on a service with this as a parameter -
Subscribe(int subscriberId, Uri channelUri);
So you need to make sure you generate a subscriberId in your app to identify a user and store it in Isolated Storage. This can be a GUID.
The onus is now upon hte server to save the Subscriber to Uri mapping in persistant storage.
Also you need to provide UnSubscribe method for user to opt out of the push notification. This is one of the certification requirement for Push notifications.
Now about your second question - Yes, you would need to secure your services - you dont want to be handling with unknown requests.
What i do personally, divide it into 2 services - Publishing service and subscription service. The Publishing service will send out hte notifications while subscription will have the subscribe/unsubscribe methods.
I guess you are trying to ask that you can send push notification from Windows Phone itself or not instead using any other server side ASP/PHP like explained in Sample Applications in MSDN. Yes. You can send notifications from phone/device itself. You have to just change Send function of Sample app as given in MSDN. Reply if you have any queries.
static async Task<string> SendPushNotification(string textToSend)
{
//You can maintain a DB to query different channel URIs of devices
string subscriptionUri = "<Uri To Which You Want Send Notification>";
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
sendNotificationRequest.Method = "POST";
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + textToSend + "</wp:Text1>" +
"<wp:Param>/NotificationDetails.xaml?Message=" + textToSend + "</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastMessage);
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers["X-WindowsPhone-Target"] = "toast";
sendNotificationRequest.Headers["X-NotificationClass"] = "2";
using (var requestStream = await Task.Factory.FromAsync<Stream>(sendNotificationRequest.BeginGetRequestStream, sendNotificationRequest.EndGetRequestStream, null))
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
string notificationStatus;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(sendNotificationRequest.BeginGetResponse, sendNotificationRequest.EndGetResponse, null)))
{
//StreamReader reader = new StreamReader(response.GetResponseStream());
//result = reader.ReadToEnd();
notificationStatus = response.Headers["X-NotificationStatus"];
MessageBox.Show(notificationStatus);
}
return notificationStatus;
}