How do i create an ACTION file AS3 - javascript

I can not understand why I get an error on the page?
How do I save the random files I get?
Every time it shows me an error regarding both files
public class Captcha extends MovieClip
{
public var captchaClip:MovieClip;
public var reloadBut:SimpleButton;
public var captchaText:TextField;
public var captchaBG:MovieClip;
private var captchaLoader:Loader = null;
private var url:String = null;
private var imageWidth:int;
private var imageHeight:int;
private var reloadButton:Object;
public function Captcha()
{
this.captchaText.defaultTextFormat = TextFormats.format(14, true, TextFormatAlign.CENTER);
this.captchaText.multiline = false;
this.captchaText.restrict = "1234567890";
this.reloadButton = getChildByName("reloadBut");
if (this.reloadButton)
{
this.reloadButton.addEventListener(MouseEvent.CLICK, this.reloadButClick, 0, false, true);
}
return;
}// end function
private function reloadButClick(event:MouseEvent) : void
{
this.reset();
event.stopImmediatePropagation();
return;
}// end function
public function getUserInput() : String
{
return this.captchaText.text;
}// end function
public function setUrl(param1:String, param2:int = 3, param3:int = 72, param4:int = 25)
{
this.url = param1;
this.imageHeight = param4;
this.imageWidth = param3;
this.captchaText.maxChars = param2;
return;
}// end function
public function reset()
{
this.captchaText.text = "";
this.loadCaptcha();
return;
}// end function
private function loadCaptcha()
{
this.captchaText.text = "";
this.captchaLoader = new Loader();
this.captchaLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.captchaLoaded);
this.captchaLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.captchaLoadError);
var _loc_1:* = new LoaderContext();
_loc_1.checkPolicyFile = true;
var _loc_2:* = new URLRequest(this.url + "?random=" + Math.random());
this.captchaLoader.load(_loc_2, _loc_1);
return;
}// end function
private function captchaLoadError(event:IOErrorEvent) : void
{
event.target.removeEventListener(Event.COMPLETE, this.captchaLoaded);
event.target.removeEventListener(IOErrorEvent.IO_ERROR, this.captchaLoadError);
return;
}// end function
private function captchaLoaded(event:Event) : void
{
event.target.removeEventListener(Event.COMPLETE, this.captchaLoaded);
event.target.removeEventListener(IOErrorEvent.IO_ERROR, this.captchaLoadError);
var _loc_2:* = event.target.content;
_loc_2.height = this.imageHeight;
_loc_2.width = this.imageWidth;
this.captchaClip.addChild(_loc_2);
return;
}// end function
}
Do I need to build these files? If so what should be inside these ACTION files?
Here you can see the errors that are created for me:
Thanks for understanding (I'm pretty new to the language so help really got needed).

You have to implement and/or connect to an existing CAPTCHA server that would provide your code with images and solutions. Your localhost:8080 web server apparently does not know how to react on your CAPTCHA requests thus returns a 404.

Related

Server Sent Events + Asp Core, why I can't make it work?

I am trying SSE just to see how they work but I can't understand why this code is not working. I am getting a client error.
In my asp controller:
public class Example {
public Example() {
X = "12";
Y = 5;
}
public string X { get; set; }
public int Y { get; set; }
}
public IActionResult Index() {
return View();
}
public async Task Messaggio() {
Response.Headers.Add("Content-Type", "text/event-stream");
var msg = System.Text.Json.JsonSerializer.Serialize(new Example());
var bytes = Encoding.ASCII.GetBytes(msg);
await Response.Body.WriteAsync(bytes, 0, bytes.Length);
await Response.Body.FlushAsync();
Response.Body.Close();
}
Client-side generated html:
<html><head>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
</head>
<body>
ciaoooo
<div id="Messaggio"></div>
<script>
source = new EventSource('/Home/Messaggio');
source.onopen = function (ddd) {
console.log("aperta");
};
source.onerror = function (ddd) {
console.log("errore");
console.log(ddd.data);
source.close();
};
source.onmessage = function (ddd) {
$("#Messaggio").text(ddd.data);
console.log(ddd.data);
};
</script>
</body>
</html>
Browser console output:
aperta
errore
undefined
routes are ok because if I request /home/messaggio it does work, I get the Json file
Thanks to anyone who can help me.
You did not add the "data" attribute before the returned "msg", so you cannot get the ddd.data value in js.
Modify the Messaggio action as follows:
public async Task Messaggio()
{
Response.Headers.Add("Content-Type", "text/event-stream");
var msg = System.Text.Json.JsonSerializer.Serialize(new Example());
var bytes = Encoding.ASCII.GetBytes($"data: {msg}\n\n");
await Response.Body.WriteAsync(bytes, 0, bytes.Length);
await HttpContext.Response.Body.FlushAsync();
Response.Body.Close();
}
Here is the result:

.net core Razor pages with JQuery AJAX

I am trying to call a Razor Page Handler using JQuery AJAX. Here is the sample code.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val() + "?handler=SelectByID";
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function () {
$("#msg").html("Error while making Ajax call!" + options.error.val);
};
$.ajax(options);
});
});
</script>
Razor Page cs code:
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
[BindProperty]
public FileRecord FileRecord { get; set; }
public List<SelectListItem> UserList { get; set; }
public string SelectedSectionId { get; set; }
public CreateModel(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
public async Task<IActionResult> OnGetAsync()
{
//Prepare UserList
UserList = new List<SelectListItem>();
List<ApplicationUser> Users = await _context.Users.ToListAsync();
foreach (var item in Users)
{
string role = Enum.GetName(typeof(EmRoles), EmRoles.NormalUser);
if (await _userManager.IsInRoleAsync(item, role) && item.IsEnabled)
{
UserList.Add(new SelectListItem()
{
Text = item.FullName,
Value = item.Id
});
}
}
//Sections
ViewData["Sections"] = new SelectList(_context.Sections, "Id", "Name");
//FileNOs
ViewData["Files"] = new SelectList(_context.FileRegisters, "Id", "FileNo");
//ViewData["ReceiverUserId"] = new SelectList(_context.Users, "Id", "Id");
//ViewData["SenderUserId"] = new SelectList(_context.Users, "Id", "Id");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//Two File Records have to be created. One For Sender & One for receiver.
FileRecord SenderRecord = new FileRecord
{
//create unique file id
//FileId = Guid.NewGuid().ToString(),
OutDate = DateTime.Now,
};
FileRecord ReceiverRecord = new FileRecord
{
//create unique file id
//FileId = SenderRecord.FileId,
InDate = SenderRecord.OutDate,
};
//Current logged-in user
var user = await GetCurrentUserAsync();
SenderRecord.OwnerUserId = user.Id;
//Receiver
ReceiverRecord.OwnerUserId = FileRecord.ReceiverUserId;
ReceiverRecord.SenderUserId = SenderRecord.OwnerUserId;
//Sender Record
if (await TryUpdateModelAsync<FileRecord>(SenderRecord, "FileRecord", f => f.FileId, f => f.Remarks, f => f.Gist, f => f.ReceiverUserId))
{
//Receiver Record
if (await TryUpdateModelAsync<FileRecord>(ReceiverRecord, "FileRecord", f => f.FileId, f => f.Gist))
{
_context.FileRecords.Add(SenderRecord);
_context.FileRecords.Add(ReceiverRecord);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
//If it reaches here. that means some error occurred.
return null;
}
}
The Issue is am not getting a call to Razor Page Handler defined above. If i skip the SectionId parameter passed-in & call only the handler. it is working fine. but it is not working when parameter is sent to the handler, default OnGet() is being called.
Help plz.
You don't need to append your handler parameter
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val();
You also need to decorate the method with the HttpGet attribute
[HttpGet("GetSelectByID")]
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
Then your URL to call this method needs to be
http://localhost:xxxx/FileMovement/Create/GetSelectByID?SectionId=yyy
When you have more than one GET defined on a controller you must tag the additional GET methods with the HttpGet attribute and add a string to define the name of that method.
Finally i was able to solve the issue.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "?handler=SelectByID" + "&SectionId=" + $("#SectionId").val();;
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function (data) {
$("#msg").html("Error while making Ajax call!" + data.error.val);
};
$.ajax(options);
});
});
Everything was right except i have to use "&" in "&SectionId="

Is it possible to return a string from C# to Javascript using Xamarin.iOS?

I have used HybridWebView from XLabs to build a HybridWebView that can communicate with C# code. I have build custom renderers to do this. In simple terms I have:
iOS
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>, IWKScriptMessageHandler
{
const string JavaScriptFunctionTemplate = "function {0}(){{window.webkit.messageHandlers.invokeAction.postMessage('{0}|' + JSON.stringify(arguments));}}";
protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
userController = new WKUserContentController();
foreach (var f in Element.RegisteredFunctions.Where(ff => !ff.IsInjected))
{
var script = new WKUserScript(new NSString(string.Format(JavaScriptFunctionTemplate, f.Name)), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript(script);
f.Injected();
}
userController.AddScriptMessageHandler(this, "invokeAction");
var config = new WKWebViewConfiguration { UserContentController = userController };
var webView = new WKWebView(Frame, config)
{
NavigationDelegate = new CustomWKNavigationDelegate(this.Element)
};
SetNativeControl(webView);
}
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
Load(Element.Uri);
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
var bits = message.Body.ToString().Split('|');
if (bits.Count() == 2)
{
var result = Element.InvokeFunction(bits[0], bits[1]);
//How do I return result back to Javascript function?
}
}
the InvokeFunction method returns a value result which is a string.
How can I return this string result back to the javascript function which was injected?
Edit
Do I need to edit my JavaScriptFunctionTemplate I notice in the XLabs they have a similar template but append something to the end
Is there any reason why you couldn't simply 're-call' your function using the methods described here?
Their example:
void OnCallJavaScriptButtonClicked (object sender, EventArgs e)
{
...
int number = int.Parse (numberEntry.Text);
int end = int.Parse (stopEntry.Text);
webView.Eval (string.Format ("printMultiplicationTable({0}, {1})", number, end));
}
So yours would be something like:
const string JavaScriptFunctionTemplate = "function {0}(){{window.webkit.messageHandlers.invokeAction.postMessage('{0}|' + JSON.stringify(arguments));}}";
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
var bits = message.Body.ToString().Split('|');
if (bits.Count() == 2)
{
var result = Element.InvokeFunction(bits[0], bits[1]);
webView.Eval(string.Format ("JavaScriptFunctionTemplate({0})", result)); // or however your parameter structure is.
}
}
EDIT:
Just want to encorporate the LINK that the OP found as it looks to be a solid guide to the solution in Objective-C which is fairly straight forward to convert to Xamarin C#.

JQuery request not working in Chrome and Firefox. Works in IE

I have a WCF service being hosted locally and a website also being hosted locally. I make a GET ajax request for JSON data which I handle on success. I have a problem where in Chrome and Firefox it goes into the error block of the Ajax request.
<!--jQuery dependencies-->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../../Library/JS/pqgrid.min.js"></script>
<script type="text/javascript">
var jqNew = $.noConflict(true);
</script>
Because of the complexity of the website, I am using two different versions of JQuery. The newer version has the alias of jqNew.
jqNew(document).ready(function () {
$($.ajax({
url: "http://wks52025:82/WcfDataService.svc/GetNotesFromView()?$format=json",
type: "GET",
datatype: "json",
async: false,
success: function (data, textStatus) {
alert(textStatus);
$.each(data.d, function (i, item) {
alert(i);
DataArray[i] = [];
DataArray[i][0] = item.NotesID;
DataArray[i][1] = item.NotesTitle;
DataArray[i][2] = item.NotesText;
DataArray[i][3] = item.ProfileName;
DataArray[i][4] = item.IsShared;
DataArray[i][5] = item.NameOfUser;
});
},
error: function (data, textStatus) {
alert(textStatus);
}
})).then(buildGrid(DataArray));
This is my request. It is synchronous because I want the data before I build my grid. It is a GET request because all I want is to retrieve data. I am not doing a cross-domain request because everything is happening locally, at least I think it's local because the website and service is localhost.
//------------------------------------------------------------------------------
// <copyright file="WebDataService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Data.Services;
using System.Data.Services.Common;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
using System.Data.Services.Parsing;
using WCFNotes;
[JSONPSupportBehavior]
public class WcfDataService : DataService< GenesisOnlineEntities >
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.UseVerboseErrors = true;
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
config.SetServiceOperationAccessRule("GetNotes", ServiceOperationRights.AllRead);
config.SetServiceOperationAccessRule("GetNotesFromView", ServiceOperationRights.AllRead);
config.SetServiceOperationAccessRule("AddNewNote", ServiceOperationRights.All);
config.SetServiceOperationAccessRule("UpdateNote", ServiceOperationRights.All);
config.SetServiceOperationAccessRule("DeleteNote", ServiceOperationRights.All);
}
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
base.OnStartProcessingRequest(args);
//Cache for a minute based on querystring
//HttpContext context = HttpContext.Current;
HttpCachePolicy c = HttpContext.Current.Response.Cache;
c.SetCacheability(HttpCacheability.NoCache);
//c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(60));
c.VaryByHeaders["Accept"] = true;
c.VaryByHeaders["Accept-Charset"] = true;
c.VaryByHeaders["Accept-Encoding"] = true;
c.VaryByParams["*"] = true;
}
[WebGet]
public IQueryable<tblNote> GetNotes()
{
IQueryable<tblNote> biglist = (from c in this.CurrentDataSource.tblNotes select c);
return biglist;
}
[WebGet]
public IQueryable<vw_Note> GetNoteByID(Guid NoteID)
{
IQueryable<vw_Note> biglist = (from c in this.CurrentDataSource.vw_Notes where c.NotesID.Equals(NoteID) select c);
return biglist;
}
[WebGet]
public IQueryable<vw_Note> GetNotesFromView()
{
Guid UserID = new Guid("8b0e303a-68aa-49a5-af95-d994e2bdd5ac");
IQueryable<vw_Note> biglist = (from c in this.CurrentDataSource.vw_Notes select c);
return biglist;
}
//[WebGet]
//public void AddNewNote(string ParamNoteTitle, string ParamNoteText)
//{
// //My hardcoded values for now...
// int ParentID = 8879;
// int JobID = 1000088150;
// int ContactID = 309;
// Guid UserID = Guid.NewGuid();
// string RelatedType = "Advertiser Contact";
// bool IsShared = true;
// tblNote N = new tblNote
// {
// NotesTitle = ParamNoteTitle,
// NotesText = ParamNoteText,
// ParentID = ParentID,
// ContactID = ContactID,
// JobID = JobID,
// UserID = UserID,
// GroupID = null,
// RelatedType = RelatedType,
// IsShared = IsShared
// };
// try
// {
// this.CurrentDataSource.tblNotes.Add(N);
// this.CurrentDataSource.SaveChanges();
// }
// catch (Exception ex)
// {
// }
//}
[WebGet]
public IQueryable<vw_Note> AddNewNote(string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
int ParentID = 8879;
int JobID = 1000088150;
int ContactID = 309;
Guid UserID = new Guid("8b0e303a-68aa-49a5-af95-d994e2bdd5ac");
Guid NoteID = Guid.NewGuid();
string RelatedType = "Advertiser Contact";
bool IsShared = true;
tblNote N = new tblNote
{
NotesID = NoteID,
NotesTitle = ParamNoteTitle,
NotesText = ParamNoteText,
ParentID = ParentID,
ContactID = ContactID,
JobID = JobID,
UserID = UserID,
GroupID = null,
RelatedType = RelatedType,
IsShared = IsShared
};
try
{
this.CurrentDataSource.tblNotes.Add(N);
this.CurrentDataSource.SaveChanges();
return GetNoteByID(NoteID);
}
catch (Exception ex)
{
return GetNoteByID(NoteID);
}
}
[WebGet]
public IQueryable<vw_Note> UpdateNote(string NoteID, string ParamNoteTitle, string ParamNoteText)
{
//My hardcoded values for now...
Guid GNoteID = Guid.Parse(NoteID);
try
{
tblNote n = CurrentDataSource.tblNotes.First(i => i.NotesID == GNoteID);
n.NotesTitle = ParamNoteTitle;
n.NotesText = ParamNoteText;
this.CurrentDataSource.SaveChanges();
return GetNoteByID(GNoteID);
}
catch (Exception ex)
{
return GetNoteByID(GNoteID);
}
}
[WebGet]
public IQueryable<vw_Note> DeleteNote(string NoteID)
{
Guid GNoteID = Guid.Parse(NoteID);
tblNote N = new tblNote
{
NotesID = GNoteID,
};
try
{
this.CurrentDataSource.tblNotes.Attach(N);
this.CurrentDataSource.tblNotes.Remove(N);
this.CurrentDataSource.SaveChanges();
// IF doesn't return value, delete was successful
return GetNoteByID(GNoteID);
}
catch (Exception ex)
{
return GetNoteByID(GNoteID);
}
}
}
This is my WCF service. Configuration is at the top of the code block.
Anyone know why this doesn't work in firefox and chrome?

GWT Native Method Warning

I'm doing a project in GWT to deploy in AppEngine and I'm getting a warning in Eclipse saying:
JavaScript parsing: Expected an identifier in JSNI
reference
Any ideas on what's causing this?
public void callFacebookAPI(String url) {
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
public void onFailure(Throwable caught) {
System.out.println("FAIL" );
}
#Override
public void onSuccess(FbUser result) {
facebookUser = result;
System.out.println("Facebook name:" + facebookUser.getName());
}
});
}
private final native void doFbLoginFunction() /*-{
FB.login(function(response) {
if (response.authResponse) {
// connected
//return response.session;
var accessToken = response.accessToken;
var url = "http://graph.facebook.com/me?access_token=";
var facebookUrl = url + accessToken;
#com.google.gwt.smartpark.client.map.SmartPark::callFacebookAPI(Ljava/lang/String;Ljava/lang/
String;)(facebookUrl);
} else {
// cancelled
}
});
callFacebookAPI is not static so there must be something before the # in the reference in JSNI, e.g.
var that = this;
$wnd.FB.login($entry(function(response) {
// ...
that.#com.google.gwt.smartpark.client.map.SmartPack::callFacebookAPI(Ljava/lang/String;)(facebookUrl);
// ...
}));
Also, your callFacebookAPI takes a single argument, so the JSNI signature should have a single Ljava/lang/String;.

Categories

Resources