here is the code to fetch username and password from the xml file but it does't fetch the the data? - flex4

Here is the code to fetch username and password from the xml file but it does't fetch the the data?
private var myXML: XML = new XML();
private function connect(event: Event): void {
var str1: String = username.text.toString();
trace(str1);
var str2: String = password.text.toString();
trace(str2);
var str3: String = myXML.authentication.username;
Alert.show(str3);
var str4: String = myXML.authentication.password;
if (str1 == str3 && str2 == str4) {
Alert.show("sucessfully Connected")
} else {
Alert.show("invalid username password");
}
}

Where you are assigning data for myXML and what is your xml?
var settingFile:File;
var stream:FileStream;
var resultXML:XML;
settingFile = settingFile.resolvePath("setting.xml");
stream = new FileStream;
if(settingFile.exists)
{
stream.open(settingFile,FileMode.READ);
resultXML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
var xmlDoc:XMLDocument = new XMLDocument(resultXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
}
from that resultObj u can access the username and password
if you are using FlexApplication then convert the xml file to xmlDocument and decode it. then from the decoded object you can get the username and password.
var xmlDoc:XMLDocument = new XMLDocument(myXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
you can try like this.
private var myXML: XML = new XML();
private function connect(event: Event): void {
var xmlDoc:XMLDocument = new XMLDocument(myXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var str1: String = username.text.toString();
trace(str1);
var str2: String = password.text.toString();
trace(str2);
var str3: String = resultObj.authentication.username;
Alert.show(str3);
var str4: String = resultObj.authentication.password;
if (str1 == str3 && str2 == str4) {
Alert.show("sucessfully Connected")
} else {
Alert.show("invalid username password");
}
}

Why don't you try to load the XML file suing the URL loader and capture the COMPLETE event to fetch the data?

Related

Image in ASP.NET MVC

I have form for upload file and i want to upload thumbnail for the file in the same form I am doing that with this part of code :
var basePath2 = Path.Combine(Directory.GetCurrentDirectory() + "\\Thumbnails\\");
bool basePathExists2 = System.IO.Directory.Exists(basePath2);
if (!basePathExists2)
Directory.CreateDirectory(basePath2);
var thumbnailPath = Path.Combine(basePath2, Thumbnail.FileName);
if (!System.IO.File.Exists(thumbnailPath))
{
using (var stream = new FileStream(thumbnailPath, FileMode.Create))
{
await Thumbnail.CopyToAsync(stream);
}
}
I am saving this model to the database:
var fileModel = new FileUploadViewModel
{
Year = createdOn,
PublishedOn = model.PublishedOn,
FileType = File.ContentType,
Extension = extension,
Name = model.Name,
Description = model.Description,
FilePath = filePath,
Author = model.Author,
ThumbnailPath = thumbnailPath,
};
When I want to show the thumbnail in a view, it doesn't work but in src I have the right path, as you can see in this screenshot:
Screenshot with Source of image
In controller :
string uniqueThumbName = null;
if (Thumbnail != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Thumbnails");
uniqueThumbName=Guid.NewGuid().ToString() + "_" + Thumbnail.FileName;
string filePath2 = Path.Combine(uploadsFolder, uniqueThumbName);
Thumbnail.CopyTo(new FileStream(filePath2, FileMode.Create));
}
var fileModel = new FileUploadViewModel
{
ThumbnailPath=uniqueThumbName,
};
In View :
var thumbPath = "~/Thumbnails/" + file.ThumbnailPath;
<img style="width:80px;height:80px;" src="#thumbPath" asp-append-version="true" />

How to update data through Api in Xamarin

I do the update command through the API. Everything seems fine. However, the data is not up to date. When I debug there is no error.
public async Task UpdateViewRatingStore(bool value)
{
var url = baseUrl + userget;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mytokenlogin);
string jsonStr = await client.GetStringAsync(url);
var res = JsonConvert.DeserializeObject<Customer>(jsonStr);
var checkunredrating = res.RatingStores;
if (checkunredrating != null)
{
foreach (var r in checkunredrating)
{
r.ID = r.ID;
r.StoreID = r.StoreID;
r.RatingStores = r.RatingStores;
r.CommentStore = r.CommentStore;
r.UserRating = r.UserRating;
r.CreateDay = r.CreateDay;
r.Display = r.Display;
r.ViewStorer = value;
var urlput = baseUrlStoreRating + r.ID;
var stringContent = new StringContent(JsonConvert.SerializeObject(res.RatingStores), Encoding.UTF8, "application/json");
await client.PutAsync(urlput, stringContent);
}
}
}
However when I check in the database it is still not updated. I tested it manually on swagger and Posman was fine. Where did I go wrong? Ask for help. Thank you
you are trying to update a single object, but passing the entire collection every time
instead, try this
foreach (var r in checkunredrating)
{
// you only need to update the changed values
r.ViewStorer = value;
var urlput = baseUrlStoreRating + r.ID;
// only send the current object you are updating
var stringContent = new StringContent(JsonConvert.SerializeObject(r), Encoding.UTF8, "application/json");
await client.PutAsync(urlput, stringContent);
}

Can't find way to debug Internal Server Error (500) caused by new class

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`
I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

Best way for store data into client

My Put method is as follows:
public void Post([FromBody]RavenUserView view)
{
if (ModelState.IsValid)
{
var request = new CreateUserRequest();
request.ID = view.ID;
request.Name = view.Name;
request.UserName = view.UserName;
request.Password = EncryptionDecryption.EncryptString(view.Password);//Encrypt The Password
request.Email = view.Email;
request.Phone = view.Phone;
request.Country = "x";
request.Note = "y";
request.IsActive = view.IsActive;
request.Creator = view.Creator;
request.CreationDate = DateTime.UtcNow;
request.ModificationDate = DateTime.UtcNow;
request.Remarks = "z";
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}
But When I run my project and try to save my information then it throw me an exception "Object Reference is not set to the reference of an object"
I am using Web Api as my controller class.
After reading various documents I found that Api is stateless. Now how can I store my user information for further use.
Use:
public void Post([Bind(Include = "ID,Name,UserName,....")] CreateUserRequest request)
{
if(ModelState.IsValid)
{
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

Resources