I want to pass three field in wwwform, which contain two single value and a json array.
Here is my Json:
{
"Fname":"Abc",
"Lname":"Xyz",
"Marks": [{"MarksA":"23","MarksB":"65" },
{"MarksA":"24","MarksB":"56" } ]
}
My current code is
void Start()
{
WWWForm form = new WWWForm();
form.AddField("Fname", "Abc");
form.AddField("Lname", "Xyz");
//passing the array as string
string Mymarks = "[{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" } ]";
form.AddField("Marks", Mymarks);
WWW www = new WWW("Urltoservice", form);
StartCoroutine("PostRequest", www);
}
IEnumerator PostRequest(WWW www)
{
yield return www;
if (www.error == null)
{
Debug.Log("Session Saved");
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
But I am getting 500 internal server Error. Please help me.
Try using WWW instead of WWWForm
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class SendData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(SendOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("TextDemo").GetComponent<Text>().text = "--------\n\n" + txt;
}
void SendOnClick()
{
try
{
GameObject.Find("TextDemo").GetComponent<Text>().text = "Starting..";
string ourPostData = "{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" }";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
byte[] jData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
WWW api = new WWW("YOUR URL", jData, headers);
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.message); }
}
}
Related
I am passing a JSON object that holds 2 Keys from React to ASP.NET Core as Follows
formData = {
image: "Base64String Here",
type: "JPEG"
}
url,
method: "POST",
data: {image: formData.image, type: formData.type},
headers: {
'Content-Type': 'application/json'
}
})
it is then collected in my controller as follows
public async Task<ActionResult<IEnumerable<AppImage>>> UploadImage()
{
string jsonString;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
jsonString = await reader.ReadToEndAsync();
}
try
{
await using var transaction = await _context.Database.BeginTransactionAsync();
SQLAppImage sqlData = new SQLAppImage(_context);
ImageHelper ih = new ImageHelper(_configuration);
//String filePath = ih.UploadImage(image, type);
//AppImage appImage = new AppImage
//{
// ImagePath = filePath,
// FileType = type
//};
//sqlData.Add(appImage);
await transaction.CommitAsync();
return Ok();
}
catch (Exception e)
{
throw e;
}
}
but i cannot seem to get the JSON object through, is there any recommendations that you might have that can help me please
Thank you in Advance
To do this, create a class as shown below :
public class UploadPhotoDto
{
public string Image { get; set; }
public string Type { get; set; }
}
and use it as your method input Like This:
[HttpPost]
public async Task<ActionResult<IEnumerable<AppImage>>>UploadImage(UploadPhotoDto uploadPhotoDto)
{
//And you can access them
string base64 = uploadPhotoDto.Image;
string type = uploadPhotoDto.Type;
//Your Code
}
I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.
I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.
Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.
So I am trying to use the Novell.Directory.Ldap.NetStandard library.
Here is the code the other developer sent me:
public static List<UserProfileModel> GetADUsers(string alias)
{
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
// Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
de2.Path = ConfigurationManager.AppSettings["AD_Path"];
de2.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de2;
deSearch.Filter = "(samaccountname=*" + alias + "*)";
LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));
SearchResultCollection results = deSearch.FindAll();
String raw = "";
LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));
if (results.Count > 0)
{
foreach (SearchResult item in results)
{
UserProfileModel userProfileModel = new UserProfileModel();
userProfileModel.Name = GetADProperty("name", item);
userProfileModel.email = GetADProperty("mail", item);
userProfileModel.identity = GetADProperty("userPrincipalName", item);
userProfileModel.first_name = GetADProperty("givenName", item);
userProfileModel.last_name = GetADProperty("sn", item);
users.Add(userProfileModel);
raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
}
LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
}
}
catch (Exception e)
{
LOGGER.Error("Unable to Query Active Directory", e);
}
return users;
}
I need to translate this into Novell's LDAP library.
Here is my attempt:
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = "ourOrg.gov";
string loginDn = #"ourOrg\myName";
string password = "myPass";
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchResults results = con.Search(
"cn=users,dc=ourOrg,dc=gov",
LdapConnection.SCOPE_ONE,
"samaccountname=*",
null,
false);
// NO RESULTS:(
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
I don't get an error.
But there are 0 results.
I originally had this part:
"samaccountname=*",
like:
"samaccountname={alias}",
but I'm just trying to get back results at this point.
I got this working:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hrsa.Core.Web.App.Controllers.Api
{
[Route("api/[controller]")]
public class ActiveDirectoryController : Controller
{
private readonly AppSettings _appSettings;
public ActiveDirectoryController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = _appSettings.HrsaLdapHost; // ourOrgName.gov
string loginDn = _appSettings.AdUser;
string password = _appSettings.AdPassword;
string searchBase = _appSettings.HrsaAdSearchBase;
string searchFilter = $"(samaccountname=*{alias}*)";
string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
"description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchQueue queue = con.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
attributes,
false,
(LdapSearchQueue)null,
(LdapSearchConstraints)null);
LdapMessage message;
while ((message = queue.getResponse()) != null)
{
if (message is LdapSearchResult)
{
LdapEntry entry = ((LdapSearchResult)message).Entry;
LdapAttributeSet attributeSet = entry.getAttributeSet();
users.Add(new UserProfileModel
{
Cn = attributeSet.getAttribute("cn")?.StringValue,
UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
St = attributeSet.getAttribute("st")?.StringValue,
Givenname = attributeSet.getAttribute("givenname")?.StringValue,
Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
Description = attributeSet.getAttribute("description")?.StringValue,
Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
Department = attributeSet.getAttribute("department")?.StringValue,
Displayname = attributeSet.getAttribute("displayname")?.StringValue,
Name = attributeSet.getAttribute("name")?.StringValue,
Mail = attributeSet.getAttribute("mail")?.StringValue,
GivenName = attributeSet.getAttribute("givenName")?.StringValue,
Sn = attributeSet.getAttribute("sn")?.StringValue
});
}
}
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
i want to check if some files exists in a folder on ftp then do specific task
i have the following methos for files check
public static bool CheckFileExistOnFTP(string ServerUri, string FTPUserName, string FTPPassword)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerUri);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
//request.Method = WebRequestMethods.Ftp.GetFileSize;
// request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
return true;
}
and i call that method on formload
if (FTPUtility.CheckFileExistOnFTP("ftp://ip address/Requests/", "edexcrawler", "edexcrawler123"))
{
btnUploadRequest.Visible = true;
btnUploadRequest.BackColor = System.Drawing.Color.LightGreen;
btnUploadRequest.ForeColor = System.Drawing.Color.Blue;
}
Based on your other question to get a list of files from ftp, you can check if the file you want to check is in that list:
Var fileNameToCkeck = "myfile.txt";
var utility= new FtpUtility();
utility.UserName = "...";
utility.Password = "...";
utility.Path = "...";
If (utility.ListFiles().Contains(fileNameToCkeck))
{
//The file exists
}
Or if you want to know if that path has any file:
If (utility.ListFiles().Count() > 0)
{
//The folder contains files
}
And here is the code for FtpUtility
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
I have seen many examples with ng-flow having the php side server to upload the files. But as I am not an expert in php and I need some help in the webapi, can someone please help me to find a working example or tutorial of ng-flow with webapi files upload.
Thanks everyone.
below is my web-api code to do this
[HttpPost]
public async Task<HttpResponseMessage> SaveFile()
{
if (!Request.Content.IsMimeMultipartContent())
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
var provider = FileSaver.GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
var fileInfo = FileSaver.MoveToTemp(result);
return Request.CreateResponse(HttpStatusCode.OK, fileInfo);
}
it uses the custom FileSaver class
public class FileSaver
{
public static MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = //your upload path;
return new MultipartFormDataStreamProvider(uploadFolder);
}
private static string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
private static string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
public static FileInfo MoveToTemp(MultipartFormDataStreamProvider result)
{
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
var folder = Directory.CreateDirectory(**); //your upload path
if (!folder.Exists) folder.Create();
var filename = folder.FullName + #"\" + originalFileName;
MoveFile(uploadedFileInfo, filename);
return uploadedFileInfo;
}
private static void MoveFile(FileInfo fileInfo, string filename)
{
var count = 0;
do
{
try
{
fileInfo.MoveTo(filename);
return;
}
catch (Exception)
{
if (count == 4)
{
throw;
}
count++;
Thread.Sleep(1 * 1000);
}
} while (true);
}
}
In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?
EDIT: code below:
MainPage:
private void button1_Click(object sender, RoutedEventArgs e)
{
Member m = new Member(name, id);
}
Member class:
public Member(String Member, String API)
{
APIKey = API;
MemberName = Member;
this.super = super;
DoSend(method, string, "", null);
}
public void DoSend(string method, string url, string body, string mimetype)
{
if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;
request.Method = method;
request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
if (body != "")
{
byte[] bodyData = Encoding.UTF8.GetBytes(body);
request.ContentType = mimetype;
//Stuff Should Happen Here
}
else
doStuff(request);
}
public void doStuff(HttpWebRequest httpReq)
{
httpReq.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
ResponseBlock.Text = response; //Invalid cross-thread reference
}
}, httpReq);
}
MainPage:
customClass.DownloadPage((result) =>
{
textBlock.Text = result;
},
(exception) =>
{
MessageBox.Show(exception.Message);
});
CustomClass:
public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
WebClient webClient = new WebClient();
webClient.DonwloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
callback(e.Result);
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
exception(e.Error);
});
}
};
webClient.DonwloadStringAsync();
}