Search Results

Search found 2069 results on 83 pages for 'anonymous delegates'.

Page 5/83 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Scoping inside Javascript anonymous functions

    - by DCD
    I am trying to make a function return data from an ajax call that I can then use. The issue is the function itself is called by many objects, e.g.: function ajax_submit (obj) { var id = $(obj).attr('id'); var message = escape ($("#"+id+" .s_post").val ()); var submit_string = "action=post_message&message="+message; $.ajax({ type: "POST", url: document.location, data: submit_string, success: function(html, obj) { alert (html); } }); return false; } Which means that inside the anonymous 'success' function I have no way of knowing what the calling obj (or id) actually are. The only way I can think of doing it is to attach id to document but that just seems a bit too crude. Is there another way of doing this?

    Read the article

  • Return/consume dynamic anonymous type across assembly boundaries

    - by friism
    The code below works great. If the Get and Use methods are in different assemblies, the code fails with a RuntimeBinderException. This is because the .Net runtime system only guarantees commonality of anonymous types (<string, int> in this case) within assemblies. Is there any way to fool the runtime system to overcome this? I can expect the object in the debugger on the Use side, and the debugger can see the relevant properties. class Program { static void Main(string[] args) { UsePerson(); Console.ReadLine(); } public static void UsePerson() { var person = GetPerson(); Console.WriteLine(person.Name); } public static dynamic GetPerson() { return new { Name = "Foo", Age = 30 }; } }

    Read the article

  • Java anonymous class efficiency implications

    - by Po
    Is there any difference in efficiency (e.g. execution time, code size, etc.) between these two ways of doing things? Below are contrived examples that create objects and do nothing, but my actual scenarios may be creating new Threads, Listeners, etc. Assume the following pieces of code happen in a loop so that it might make a difference. Using anonymous objects: void doSomething() { for (/* Assume some loop */) { final Object obj1, obj2; // some free variables IWorker anonymousWorker = new IWorker() { doWork() { // do things that refer to obj1 and obj2 } }; } } Defining a class first: void doSomething() { for (/* Assume some loop */) { Object obj1, obj2; IWorker worker = new Worker(obj1, obj2); } } static class Worker implements IWorker { private Object obj1, obj2; public CustomObject(Object obj1, Object obj2) {/* blah blah */} @Override public void doWork() {} }; Thank you :)

    Read the article

  • Where to put constant strings in C++: static class members or anonymous namespaces

    - by stone
    I need to define some constant strings that will be used only by one class. It looks like I have three options: Embed the strings directly into locations where they are used. Define them as private static constant members of the class: //A.h class A { private: static const std::string f1; static const std::string f2; static const std::string f3; }; //A.cpp const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; //strings are used in this file Define them in an anonymous namespace in the cpp file: //A.cpp namespace { const std::string f1 = "filename1"; const std::string f2 = "filename2"; const std::string f3 = "filename3"; } //strings are used in this file Given these options, which one would you recommend and why? Thanks.

    Read the article

  • Silverlight datagrid don't show any data with anonymous query RIA services

    - by user289082
    Hi all! I have an anonymous linq query that I bind to a datagrid, when I debug it brings alright the data but it doesn't show in the datagrid, I suspect that the request to RIA services isn't completed before I bound it to the datagrid. I could use the LoadOperation<() Completed event. But it only works with Defined Entities so how can I do that? For reference here is the last post: http://stackoverflow.com/questions/2403903/linq-query-null-reference-exception Here is the query: var bPermisos = from b in ruc.Permisos where b.IdUsuario == SelCu.Id select new { Id=b.Id, IdUsuario=b.IdUsuario, IdPerfil=b.IdPerfil, Estatus=b.Estatus, Perfil=b.Cat_Perfil.Nombre, Sis=b.Cat_Perfil.Cat_Sistema.Nombre }; I'm a totally newbie sorry if is a very simple question. Thanks!!

    Read the article

  • matlab constant anonymous function returns only one value instead of an array

    - by Filo
    I've been searching the net for a couple of mornings and found nothing, hope you can help. I have an anonymous function like this f = @(x,y) [sin(2*pi*x).*cos(2*pi*y), cos(2*pi*x).*sin(2*pi*y)]; that needs to be evaluated on an array of points, something like x = 0:0.1:1; y = 0:0.1:1; w = f(x',y'); Now, in the above example everything works fine, the result w is a 11x2 matrix with in each row the correct value f(x(i), y(i)). The problem comes when I change my function to have constant values: f = @(x,y) [0, 1]; Now, even with array inputs like before, I only get out a 1x2 array like w = [0,1]; while of course I want to have the same structure as before, i.e. a 11x2 matrix. I have no idea why Matlab is doing this...

    Read the article

  • Anonymous method as function result

    - by iamjoosy
    What I want to do is to assign an anonymous method which I get as a function result to a variable of the same type. Delphi complains about not beeing able to do the assignement. Obviously Delphi things I want to assign the "GetListener" function instead of the result of that same function. Any help with this is very much appreciated. type TPropertyChangedListener = reference to procedure (Sender: TStimulus); TMyClass = class function GetListener:TPropertyChangedListener end; .... var MyClass: TMyClass; Listener: TPropertyChangedListener; begin MyClass:= TMyClass.create; Listener:= MyClass.GetListener; // Delphi compile error: E2010 Incompatible types: TPropertyChangedListener' and 'Procedure of object' end;

    Read the article

  • Creating anonymous functions in loop with not the same arguments

    - by onio9
    Hello! I want to make in loop set of buttons, and add to them some events, but anonymous functions is the same. I write example code: for(var i:int=0;i<5;i++) { var button:SimpleButton = new SimpleButton(...); ... button.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void { trace(i); }); } ... And I want to trace 1,2,3.. from click buttons instead of 4,4,4,4 .. Do you know how can I make this ?

    Read the article

  • Anonymous Access and Sharepoint Web Services

    - by Stacy Vicknair
    A month or so ago I was working on a feature for a project that required a level of anonymity on the Sharepoint site in order to function. At the same time I was also working on another feature that required access to the Sharepoint search.asmx web service. I found out, the hard way, that the Sharepoint Web Services do not operate in an expected way while the IIS site is under anonymous access. Even though these web services expect requests with certain permissions (in theory) they never attempt to request those credentials when the web service is contacted. As a result the services return a 401 Unauthorized response. The fix for my situation was to restrict anonymous access to the area that needed it (in this case the control in question had support for being used in an ASP.NET app that I could throw in a virtual directory). After that I removed anonymous access from IIS for the site itself and the QueryService requests were working once more. Here’s a related article with a bit more depth about a similar experience: http://chrisdomino.com/Blog/Post/401-Reasons-Why-SharePoint-Web-Services-Don-t-Work-Anonymously?Length=4 Technorati Tags: Sharepoint,QueryService,WSS,IIS,Anonymous Access

    Read the article

  • the HTTP request is unauthorized with client authentication scheme 'Anonymous'

    - by user1246429
    I use firstdata webservice API.I use C# client call firstdata webservice API with WCF. But show error message: "But show error message "System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was ''. --- System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) --- End of inner exception stack trace --- Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory) at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at com.firstdata.globalgatewaye4.api.ServiceSoap.SendAndCommit(SendAndCommitRequest request) at com.firstdata.globalgatewaye4.api.ServiceSoapClient.com.firstdata.globalgatewaye4.api.ServiceSoap.SendAndCommit (SendAndCommitRequest request) at com.firstdata.globalgatewaye4.api.ServiceSoapClient.SendAndCommit(Transaction SendAndCommitSource)" My web.config info below: <behaviors> <endpointBehaviors> <behavior name="FDGGBehavior"> <clientCredentials> <clientCertificate findValue="WS1909642825._.1" storeLocation="LocalMachine" x509FindType="FindBySubjectName" storeName="TrustedPeople" /> <serviceCertificate> <authentication certificateValidationMode="PeerTrust" /> </serviceCertificate> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> <binding name="ServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="Certificate" proxyCredentialType="Ntlm" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> <endpoint address="https://api.globalgatewaye4.firstdata.com/transaction/v11" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="com.firstdata.globalgatewaye4.api.ServiceSoap" name="ServiceSoap" behaviorConfiguration="FDGGBehavior" /> How can resolve question?

    Read the article

  • access exception when invoking method of an anonymous class using java reflection

    - by Asaf David
    Hello I'm trying to use an event dispatcher to allow a model to notify subscribed listeners when it changes. the event dispatcher receives a handler class and a method name to call during dispatch. the presenter subscribes to the model changes and provide a Handler implementation to be called on changes. Here's the code (I'm sorry it's a bit long). EventDispacther: package utils; public class EventDispatcher<T> { List<T> listeners; private String methodName; public EventDispatcher(String methodName) { listeners = new ArrayList<T>(); this.methodName = methodName; } public void add(T listener) { listeners.add(listener); } public void dispatch() { for (T listener : listeners) { try { Method method = listener.getClass().getMethod(methodName); method.invoke(listener); } catch (Exception e) { System.out.println(e.getMessage()); } } } } Model: package model; public class Model { private EventDispatcher<ModelChangedHandler> dispatcher; public Model() { dispatcher = new EventDispatcher<ModelChangedHandler>("modelChanged"); } public void whenModelChange(ModelChangedHandler handler) { dispatcher.add(handler); } public void change() { dispatcher.dispatch(); } } ModelChangedHandler: package model; public interface ModelChangedHandler { void modelChanged(); } Presenter: package presenter; public class Presenter { private final Model model; public Presenter(Model model) { this.model = model; this.model.whenModelChange(new ModelChangedHandler() { @Override public void modelChanged() { System.out.println("model changed"); } }); } } Main: package main; public class Main { public static void main(String[] args) { Model model = new Model(); Presenter presenter = new Presenter(model); model.change(); } } Now, I except to get the "model changed" message. However, I'm getting an java.lang.IllegalAccessException: Class utils.EventDispatcher can not access a member of class presenter.Presenter$1 with modifiers "public". I understand that the class to blame is the anonymous class i created inside the presenter, however I don't know how to make it any more 'public' than it currently is. If i replace it with a named nested class it seem to work. It also works if the Presenter and the EventDispatcher are in the same package, but I can't allow that (several presenters in different packages should use the EventDispatcher) any ideas?

    Read the article

  • When is it useful to define your own delegates instead of using the generics?

    - by Carlos
    I've been going through some old code, where I came across some custom defined delegates, which are used thus: private delegate void ListenDelegate(UdpClient listener, bool multicast); private void ListenOn(UdpClient listener, bool multicast) { new ListenDelegate(_ListenLoop).BeginInvoke(listener, multicast, null, null); } With some of the new .NET framework versions, you can do the following: private void ListenOn(UdpClient listener, bool multicast) { new Action<UdpClient, bool>(_ListenLoop).BeginInvoke(listener, multicast, null, null); } This ought to be exactly the same. Is there any point in defining your own delegates, when the generic delegates seem to do the same job with less space? Or have I missed something about the generics that makes them not equivalent?

    Read the article

  • Django anonymous user in model

    - by jack
    I have a model defined as below: class Example(models.Model): user = models.ForeignKey(User, null=True) other = models.CharField(max_length=100) The problem is Django refuses to assign django.contrib.auth.models.AnonymousUser directly to Example.user as null field so everytime I have to check if request.user.is_authenticated() ans assign Example.user = None manually. Is there a default value for AnonymousUser to use in a model field?

    Read the article

  • CoffeeScript Class Properties Within Nested Anonymous Functions

    - by Aric
    I'm just taking a look at CoffeeScript for the first time so bare with me if this is a dumb question. I'm familiar with the hidden pattern methodology however I'm still wrapping my head around object prototypes. I'm trying to create a basic class for controlling a section on my site. The problem I'm running into is losing defined class variables within a different scope. For example, the code below works fine and creates the properties within the object perfectly. However when I jump into a jQuery callback I lose all knowledge of the class variables storing some of the jQuery objects for multiple uses. Is there a way to grab them from within the callback function? class Session initBinds: -> @loginForm.bind 'ajax:success', (data, status, xhr) -> console.log("processed") return @loginForm.bind 'ajax:before', (xhr, settings) -> console.log @loader // need access to Session.loader return return init: -> @loginForm = $("form#login-form") @loader = $("img#login-loader") this.initBinds() return

    Read the article

  • anonymous function variable scope [js, ajax]

    - by arthurprs
    $(".delete").click( function() { var thesender = this; $(thesender).text("Del..."); $.getJSON("ajax.php", {}, function(data) { if (data["result"]) $(thesender).remove(); // variable defined outside else alert('Error!'); } ); return false; } ); This can cause problems if user clicks on another ".delete" before the ajax callback is called?

    Read the article

  • PHP anonymous functions scope question

    - by Dan
    Hi, I'm trying to sort an array of objects by a common property, however I cannot get my $property parameter to register in the inner function (I can use it in the outer one OK). The way I read the documentation, it sounded like the parameter would be available, have I misunderstood something? Here is what I have: public static function sortObjectsByProperty($objects, $property) { function compare_object($a, $b) { $a = $a->$property; $b = $b->$property; if ($a->$property == $b->$property) { return 0; } return ($a->$property > $b->$property) ? +1 : -1; } usort($objects, 'compare_object'); return $objects; } Any advice appreciated. Thanks.

    Read the article

  • Self-Executing Anonymous Function vs Prototype

    - by Robotsushi
    In Javascript there are a few clearly prominent techniques for create and manage classes/namespaces in javascript. I am curious what situations warrant using one technique vs. the other. I want to pick one and stick with it moving forward. I write enterprise code that is maintained and shared across multiple teams, and I want to know what is the best practice when writing maintainable javascript ? I tend to prefer Self-Executing Anonymous Functions however I am curious what the community vote is on these techniques. Prototype : function obj() { } obj.prototype.test = function() { alert('Hello?'); }; var obj2 = new obj(); obj2.test(); Self-Closing Anonymous Function : //Self-Executing Anonymous Function (function( skillet, $, undefined ) { //Private Property var isHot = true; //Public Property skillet.ingredient = "Bacon Strips"; //Public Method skillet.fry = function() { var oliveOil; addItem( "\t\n Butter \n\t" ); addItem( oliveOil ); console.log( "Frying " + skillet.ingredient ); }; //Private Method function addItem( item ) { if ( item !== undefined ) { console.log( "Adding " + $.trim(item) ); } } }( window.skillet = window.skillet || {}, jQuery )); //Public Properties console.log( skillet.ingredient ); //Bacon Strips //Public Methods skillet.fry(); //Adding Butter & Fraying Bacon Strips //Adding a Public Property skillet.quantity = "12"; console.log( skillet.quantity ); //12 //Adding New Functionality to the Skillet (function( skillet, $, undefined ) { //Private Property var amountOfGrease = "1 Cup"; //Public Method skillet.toString = function() { console.log( skillet.quantity + " " + skillet.ingredient + " & " + amountOfGrease + " of Grease" ); console.log( isHot ? "Hot" : "Cold" ); }; }( window.skillet = window.skillet || {}, jQuery )); //end of skillet definition try { //12 Bacon Strips & 1 Cup of Grease skillet.toString(); //Throws Exception } catch( e ) { console.log( e.message ); //isHot is not defined } I feel that I should mention that the Self-Executing Anonymous Function is the pattern used by the jQuery team. Update When I asked this question I didn't truly see the importance of what I was trying to understand. The real issue at hand is whether or not to use new to create instances of your objects or to use patterns which do not require constructors of the use of the new keyword. I added my own answer, because in my opinion we should make use of patterns which don't use the new keyword. For more information please see my answer.

    Read the article

  • Anonymous functions in C#

    - by Maxim Gershkovich
    The following syntax is valid VB.NET code Dim myCollection As New List(Of Stock) myCollection.Add(New Stock(Guid.NewGuid, "Item1")) myCollection.Add(New Stock(Guid.NewGuid, "Item2")) Dim res As List(Of Stock) = myCollection.FindAll(Function(stock As Stock) As Boolean If stock.Description = "Item2" Then Return True End If Return False End Function) How can I accomplish the same thing in C#? I have tried... myCollection.FindAll(bool delegate(Stock stock) { if (blah blah) { } }); But it appears I have somehow structured it incorrectly as I get the following error. "Error 1 Invalid expression term 'bool'"

    Read the article

  • Anonymous functions IE issue/problem in Javascript

    - by Bragaadeesh
    Hi guys, I am having a javascript written like this. imageDiv.onclick = function(){xyz.deleteImage(param1, param2);return false;}; Now things are fine in Firefox, Chrome and Safari. But I have a strange issue in Internet Explorer. What happens is, when I click on the imageDiv in my page, the deleteImage() method is getting invoked twice. One being the actual deleteimage() method thats given here and another is the deleteimage() method that I have in the page. How to resolve this issue. Please help.

    Read the article

  • Templated Razor Delegates – Phil Haack

    - by nmarun
    This post is largely based off of Phil Haack’s article titled Templated Razor Delegates. I strongly recommend reading this article first. Here’s a sample code for the same, so you can have a look at. I also have a custom type being rendered as a table. 1: // my custom type 2: public class Device 3: { 4: public int Id { get; set; } 5: public string Name { get; set; } 6: public DateTime MfgDate { get; set; } 7: } Now I can write an extension method just for this type. 1: public static class RazorExtensions 2: { 3: public static HelperResult List(this IList<Models.Device> devices, Func<Models.Device, HelperResult> template) 4: { 5: return new HelperResult(writer => 6: { 7: foreach (var device in devices) 8: { 9: template(device).WriteTo(writer); 10: } 11: }); 12: } 13: // ... 14: } Modified my view to make it a strongly typed one and included html to render my custom type collection in a table. 1: @using TemplatedRazorDelegates 2: @model System.Collections.Generic.IList<TemplatedRazorDelegates.Models.Device> 3:  4: @{ 5: ViewBag.Title = "Home Page"; 6: } 7:  8: <h2>@ViewBag.Message</h2> 9:  10: @{ 11: var items = new[] { "one", "two", "three" }; 12: IList<int> ints = new List<int> { 1, 2, 3 }; 13: } 14:  15: <ul> 16: @items.List(@<li>@item</li>) 17: </ul> 18: <ul> 19: @ints.List(@<li>@item</li>) 20: </ul> 21:  22: <table> 23: <tr><th>Id</th><th>Name</th><th>Mfg Date</th></tr> 24: @Model.List(@<tr><td>@item.Id</td><td>@item.Name</td><td>@item.MfgDate.ToShortDateString()</td></tr>) 25: </table> We get intellisense as well! Just added some items in the action method of the controller: 1: public ActionResult Index() 2: { 3: ViewBag.Message = "Welcome to ASP.NET MVC!"; 4: IList<Device> devices = new List<Device> 5: { 6: new Device {Id = 1, Name = "abc", MfgDate = new DateTime(2001, 10, 19)}, 7: new Device {Id = 2, Name = "def", MfgDate = new DateTime(2011, 1, 1)}, 8: new Device {Id = 3, Name = "ghi", MfgDate = new DateTime(2003, 3, 15)}, 9: new Device {Id = 4, Name = "jkl", MfgDate = new DateTime(2007, 6, 6)} 10: }; 11: return View(devices); 12: } Running this I get the output as: Absolutely brilliant! Thanks to both Phil Haack and to David Fowler for bringing this out to us. Download the code for this from here. Verdict: RazorViewEngine.Points += 1;

    Read the article

  • Issue with translating a delegate function from c# to vb.net for use with Google OAuth 2

    - by Jeremy
    I've been trying to translate a Google OAuth 2 example from C# to Vb.net for a co-worker's project. I'm having on end of issues translating the following methods: private OAuth2Authenticator<WebServerClient> CreateAuthenticator() { // Register the authenticator. var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; return authenticator; } private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return state; } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return state; } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; } The main issue being this line: var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; The Method signature reads as for this particular line reads as follows: Public Sub New(tokenProvider As TClient, authProvider As System.Func(Of TClient, DotNetOpenAuth.OAuth2.IAuthorizationState)) My understanding of Delegate functions in VB.net isn't the greatest. However I have read over all of the MSDN documentation and other relevant resources on the web, but I'm still stuck as to how to translate this particular line. So far all of my attempts have resulted in either the a cast error (see below) or no call to GetAuthorization. The Code (vb.net on .net 3.5) Private Function CreateAuthenticator() As OAuth2Authenticator(Of WebServerClient) ' Register the authenticator. Dim client As New WebServerClient(GoogleAuthenticationServer.Description, oauth.ClientID, oauth.ClientSecret) Dim authDelegate As Func(Of WebServerClient, IAuthorizationState) = AddressOf GetAuthorization Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, authDelegate) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, GetAuthorization(client)) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(Function(c) GetAuthorization(c))) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(AddressOf GetAuthorization)) With {.NoCaching = True} Return authenticator End Function Private Function GetAuthorization(arg As WebServerClient) As IAuthorizationState ' If this user is already authenticated, then just return the auth state. Dim state As IAuthorizationState = AuthState If (Not state Is Nothing) Then Return state End If ' Check if an authorization request already is in progress. state = arg.ProcessUserAuthorization(New HttpRequestInfo(HttpContext.Current.Request)) If (state IsNot Nothing) Then If ((String.IsNullOrEmpty(state.AccessToken) = False Or String.IsNullOrEmpty(state.RefreshToken) = False)) Then ' Store Credentials HttpContext.Current.Session("AUTH_STATE") = state _state = state Return state End If End If ' Otherwise do a new authorization request. Dim scope As String = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() Dim _response As OutgoingWebResponse = arg.PrepareRequestUserAuthorization(New String() {scope}) ' Add Offline Access and forced Approval _response.Headers("location") += "&access_type=offline&approval_prompt=force" _response.Send() ' Will throw a ThreadAbortException to prevent sending another response. Return Nothing End Function The Cast Error Server Error in '/' Application. Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. I've spent the better part of a day on this, and it's starting to drive me nuts. Help is much appreciated.

    Read the article

  • Why is one Func valid and the other (almost identical) not.

    - by runrunraygun
    private static Dictionary<Type, Func<string, object>> _parseActions = new Dictionary<Type, Func<string, object>> { { typeof(bool), value => {Convert.ToBoolean(value) ;}} }; The above gives an error Error 14 Not all code paths return a value in lambda expression of type 'System.Func<string,object>' However this below is ok. private static Dictionary<Type, Func<string, object>> _parseActions = new Dictionary<Type, Func<string, object>> { { typeof(bool), value => Convert.ToBoolean(value) } }; I don't understand the difference between the two. I thought the extra braces in example1 are to allow us to use multiple lines in the anon function so why have they affected the meaning of the code?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >