Backload Example #4 code not working.
public class FileUploadDerivedController : BackloadController
{
// Since version 1.9 you can call the asynchronous handler method
public async Task<ActionResult> FileHandler()
{
// Call base class method to handle the file upload asynchronously
ActionResult result = await base.HandleRequestAsync();
return result;
}
}
I get this error:
'Backload.Controllers.BackloadController' does not contain a definition for 'HandleRequestAsync'
To reproduce:
Using VS2010, open new MVC4 project.
To enable async in VS2010, Install VS Async CTP: http://www.microsoft.com/en-us/download/details.aspx?id=9983
In your project, reference: [VS Async CTP Install]\Microsoft Visual Studio Async CTP\Samples\AsyncCtpLibrary.dll
Using Package Manager Command
Install-Package Backload
Download Examples from: https://github.com/blackcity/Backload
Open Example #4 and copy the code from FileUploadController.cs for FileUploadDerivedController class.
usings
using Backload.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Backload;
using System.Threading.Tasks;
Controller
// Change namespace to yours
namespace Backload.Examples.Example04.Controllers
{
// For all demos below open the file ~/Scripts/main.js and
// change the url of the ajax call for the fileupload plugin
// Demo 1: Derive from BackloadController and call the base class
public class FileUploadDerivedController : BackloadController
{
// Since version 1.9 you can call the asynchronous handler method
public async Task<ActionResult> FileHandler()
{
// Call base class method to handle the file upload asynchronously
ActionResult result = await base.HandleRequestAsync();
return result;
}
}
}
Error should occur on this line
ActionResult result = await base.HandleRequestAsync();
The error is correct.
VS2010 with the Async CTP is not stable and certainly not recommended for production use. Please note that it is not easy to even create this development environment anymore, since the Async CTP is blocked by a number of Windows Updates.
But even if you use VS2012 (i.e., with Microsoft.Bcl.Async), this still won't work because async behavior is undefined on ASP.NET 4.
To use async on MVC, you must use ASP.NET 4.5 (or higher), and this means using VS2012.
Related
Following this tutorial, https://learn.microsoft.com/en-us/xamarin/essentials/secure-storage?tabs=android
I have installed Xamarin.Essentials and added using Xamarin.Essentials; as instructed but it is not in used.
I got this error: 'securestorage' does not contain a definition for setasync
Here is my code:
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Xamarin_SQLite.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SecureStorage : ContentPage
{
public SecureStorage()
{
InitializeComponent();
try
{
SecureStorage.SetAsync("oauth_token", "secret-oauth-token-value");
}
catch (Exception ex)
{
// Possible that device doesn't support secure storage on device.
}
}
}
}
'securestorage' does not contain a definition for setasync
1) Your class name for the page is SecureStorage and that is where the error is coming from.
Change the class name and|or fully qualify the call to:
`Xamarin.Essentials.SecureStorage.SetAsync`
or create a using alias for Xamarin.Essentials and qualify the static method with that alias)
2) You need to await that call:
`await Xamarin.Essentials.SecureStorage.SetAsync...`
I have a pretty massive iOS Framework to bind.
This framework depends on two others.
I created the binding project, successfully generated the ApiDefinitions.cs file and StructsAndEnums.cs. So far so good.
Now, when I try to build it in Debug mode, I get about 30+ errors regarding syntax issues in temporary files.
These errors only occur in Trampolines.g.cs, and SupportDelegates.g.cs files.
The worst of the two is the SupportDelegates.g.cs file which looks like this :
//
// Auto-generated from generator.cs, do not edit
//
// We keep references to objects, so warning 414 is expected
#pragma warning disable 414
using System;
using System.Drawing;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using UIKit;
using GLKit;
using Metal;
using MapKit;
using Photos;
using ModelIO;
using SceneKit;
using Contacts;
using Security;
using Messages;
using AudioUnit;
using CoreVideo;
using CoreMedia;
using QuickLook;
using CoreImage;
using SpriteKit;
using Foundation;
using CoreMotion;
using ObjCRuntime;
using AddressBook;
using MediaPlayer;
using GameplayKit;
using CoreGraphics;
using CoreLocation;
using AVFoundation;
using NewsstandKit;
using FileProvider;
using CoreAnimation;
using CoreFoundation;
namespace System.Action`1[[Foundation.NSString, Xamarin.iOS, Version=0.0.0 {
public delegate void 0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065]] (NSString obj);
}
The Trampolines.g.cs file is generating almost completely, but the same kind of issue appears in the middle of the generated C# code:
static internal class SDActionArity2V1 {
static internal readonly DActionArity2V1 Handler = Invoke;
[MonoPInvokeCallback (typeof (DActionArity2V1))]
static unsafe void Invoke (IntPtr block, IntPtr arg1, IntPtr arg2) {
var descriptor = (BlockLiteral *) block;
var del = (global::System.Action<NSString, global::System.Action<NSString>>) (descriptor->Target);
if (del != null)
del ( Runtime.GetNSObject<NSString> (arg1), (System.Action`1[Foundation.NSString]) Marshal.GetDelegateForFunctionPointer (arg2, typeof (System.Action`1[Foundation.NSString])));
}
}
Some other binding projects is generating the same kind of files, and eveything seems to be working fine, so I'm actually struggling to find the root cause of this.
Any ideas ?
EDIT:
To give more infos here is the generated interface definition
https://gist.github.com/Miiite/367e17335431e932acdc92c65b504bd4
EDIT2: Here is what sharpie generated as log output
https://gist.github.com/Miiite/e272622df2e853d53f1add4c8eb4eabf
I believe the issue is here:
void PresentCheckoutForSubmittingTransactionCompletionHandler(Action<OPPTransaction, NSError> completionHandler, [NullAllowed] Action<NSString, Action<NSString>> paymentBrandSelectedHandler, [NullAllowed] Action cancelHandler);
I think the Action inside the Action is causing the problem, the generator might not support this, so you might need to find a different way of binding that.
This problematic method can definitely be bound, if you need it here is how (I omitted the rest of the class members for brevity):
delegate void OPPPaymentBrandSelectedHandler (string paymentBrand, [BlockCallback] OPPPaymentCompletionHandler completionHandler);
delegate void OPPPaymentCompletionHandler ([NullAllowed] string checkoutId);
[BaseType (typeof (NSObject))]
interface OPPCheckoutProvider {
// -(void)presentCheckoutForSubmittingTransactionCompletionHandler:(void (^ _Nonnull)(OPPTransaction * _Nullable, NSError * _Nullable))completionHandler
// paymentBrandSelectedHandler:(void (^ _Nullable)(NSString * _Nonnull, void (^ _Nonnull)(NSString * _Nullable)))paymentBrandSelectedHandler
// cancelHandler:(void (^ _Nullable)(void))cancelHandler;
[Export("presentCheckoutForSubmittingTransactionCompletionHandler:paymentBrandSelectedHandler:cancelHandler:")]
void PresentCheckoutForSubmittingTransactionCompletionHandler(Action<OPPTransaction, NSError> completionHandler, [NullAllowed] OPPPaymentBrandSelectedHandler paymentBrandSelectedHandler, [NullAllowed] Action cancelHandler);
}
The trick is to instead of using nested Actions you need to break it into two delegates and use the BlockCallback attribute to instruct the generator that the parameter should be marshaled as an ObjC block, then just use the parent delegate as the type of the paymentBrandSelectedHandler parameter inside the PresentCheckoutForSubmittingTransactionCompletionHandler method.
Hope this helps to get you completely unblocked. That said we should report a much better error, I'll discuss with the team and have a look.
Cheers!
I have set up a signalR website .net core. My function in my hub is:
public async Task Notify(int id) {
await Clients.All.InvokeAsync("Notified", id);
}
I have also tested this with the following js:
let connection = new signalR.HubConnection(myURL);
connection.on('Notified', data => {
console.log(4, data);
});
connection.start();
The js code seems to work fine and I see the log when I try connection.Invoke('Notify').
Now I have a console app that can needs to make the invoke. I am trying this in two ways and don't mind either solution:
1. A mvc controller within the signalR website that can take the id and invoke 'Notified'.
2. Use the client library Microsoft.AspNetCore.SignalR.Client in the console app.
The way 1 I have only done in classic asp.net like this:
GlobalHost.ConnectionManager.GetHubContext(hubName)
But couldn't find a way to do this in .net core.
Way 2 I have used the library and tried this so far:
var con = new HubConnectionBuilder();
con.WithUrl(myURL);
var connection = con.Build();
connection.InvokeAsync("Notify",args[0]).Wait();
This is the closest I have come to create a connection in the same way as the js code. However this code throws a null pointer when calling connection.InvokeAsync. The connection object is not null. It seems to be an internal object that is null. According to the stack trace the exception is thrown when a MoveNext() function is internally called.
Well looks like both are not currently possible. As of now I just used a forced way which is hopefully temporary.
I have created and used the following base class for hubs:
public abstract class MyHub : Hub
{
private static Dictionary<string, IHubClients> _clients = new Dictionary<string, IHubClients>();
public override Task OnConnectedAsync()
{
var c = base.OnConnectedAsync();
_clients.Remove(Name);
_clients.Add(Name, Clients);
return c;
}
public static IHubClients GetClients(string Name) {
return _clients.GetValueOrDefault(Name);
}
}
GlobalHost is gone. You need to inject IHubContext<THub> like in this sample.
This can be a bug in SignalR alpha1. Can you file an issue on https://github.com/aspnet/signalr and include a simplified repro?
I'm developing a library of OData queries using Web Api and ODataController. When I go to run my api from a web browser it returns nothing. I don't get an error of any kind. I can debug in Visual Studio and see clearly that the method runs and successfully returns my results as an IQueryable<>. Somewhere under the hood it's discarding my data. Has anyone else seen or encountered this? I've included my code below for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using Epm.Core.Model;
using System.Web.Http.OData.Query;
using Epm.Data.Access;
using Epm.Service.Assemblers;
namespace Epm.Service.Web.Controllers.OData
{
public class SearchActionsController : ODataController
{
private readonly EpmEntities context = new EpmEntities();
[Queryable(AllowedQueryOptions=AllowedQueryOptions.All)]
public IQueryable<ActionStepDisplay> Get(int planId, int? factorId, bool? showArchived)
{
var user = this.GetCurrentUser();
var results = (from p in context.SearchActions(user.SessionId, planId, factorId, showArchived, 1, null)
select p).ToModel().ToArray();
return results.AsQueryable();
}
protected override void Dispose(bool disposing)
{
context.Dispose();
base.Dispose(disposing);
}
}
}
My configuration:
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Epm.Core.Model.ActionStep>("SearchActions");
Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("ODataRoute", "odata", model);
You are returning ActionStepDisplay from your method, but in builder you specified ActionStep as the entity.
May be Not Acceptable (406) in the response header
Possibly the problem lies with the MediaFormatter, which gets called after the controller has finished. When a media type formatter encounters a reference loop (where object A reference B and B references A) then you need to tell the media type formatter how to handle that, so in the Json Media Type Formatter you do something like...
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
See Documentation Here
I'd recommend you use Fiddler to see what is actually going on. You say your not getting a response in the browser, so what HTTP code is returned? You can use Fiddler to find out...
How to get all the publishing items by code when a directory is being published and which event should I add my handler to, publish:begin or publish:itemProcessing?
If you're looking to setup a custom event handler start with the web.config reference.
<event name="publish:begin">
<handler type="YourNamespace.YourClass, YourLibrary" method="YourHandlerMethod" />
</event>
Then create a class that will support this reference.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Sitecore.Diagnostics;
using Sitecore.Sites;
using Sitecore.Configuration;
using Sitecore.Caching;
using Sitecore.Events;
using Sitecore.Publishing;
using Sitecore.Data.Events;
using Sitecore.Data;
using Sitecore.Data.Items;
namespace YourNamespace {
public class YourClass {
public void YourHandlerMethod(object sender, EventArgs args) {
Assert.ArgumentNotNull(sender, "sender");
Assert.ArgumentNotNull(args, "args");
//try to get the sitecore event args
if (args.GetType().ToString().Equals("Sitecore.Events.SitecoreEventArgs")) {
SitecoreEventArgs sargs = (SitecoreEventArgs)args;
foreach (object o in sargs.Parameters) {
//try to get the publisher object
if (o.GetType().ToString().Equals("Sitecore.Publishing.Publisher")) {
Publisher p = (Publisher)o;
if (p != null) {
Item root = p.Options.RootItem;
bool b = p.Options.RepublishAll;
if(p.Options.Mode.Equals(PublishMode.SingleItem)){
//only one item published
}
}
}
}
}
}
}
}
From this class you can try to access the publisher object which will give you the root item published and publish options. The publish options will tell you if there was a single item published or if it published all versions of languages.
Depending on your real needs, it might make more sense to inject a custom processor into the publishItem pipeline rather than use publish:itemProcessing event. If you take a closer look at that pipeline (search for "<publishItem") in web.config, you'll that those events (publish:itemProcessing and publish:itemProcessed) are generated by the appropriate processors of pipeline.
NOTE: the publishing process is rather complex and I would not recommend doing anything with the item being published that can influence the process in general. I can't give you an example here - only your fantasy sets the limits...
Note also, that with those events, as well as the pipeline I mentioned, you operate with 1 item at a time - it will be called for each item being published. This can become performance critical...
UPDATE: You can read more about pipeline in this blog post. Apart from being useful itself, it contains more useful links on the subject.