Generics (return type error)

Hi to everyone, I'm new around there!
I have 2 questions to ask:
I tryed to implement a generic tree inside of wich I created a "search" method.
This method needs the method "compareTo" of the class "Comparable" to compare nodes, so the tree class requires a bound and the header is the following:
public class BTNodeGen <T extends Comparable>
The problem is that in this whay the search method returns a Comparable instead of a generic type. The method is the following:
public <T extends Comparable> T search(T el)
          if (el.compareTo(key)==0)
               return(el);
          else if((el.compareTo(key)<0) && (left != null))
               return ((T)left.search(el));
          else if(right != null)
               return ((T)right.search(el));
          else
               return null;
     }This method works and returns a T only because I added some downcast to T before the return, otherwise it gives a compile error because it is returned a Comparable where is expected a T.
How can I do to avoid downcasts (that aren't so much correct for a OO language...)?
Can you help me?
A last question: what changes between the following header of the method search:
- public <T extends Comparable> T search(T el)
- public T search(T el)
and between the following class header
- public class BTNodeGen<T extends Comparable>
- public class BTNodeGen<T extends Comparable<T>>
Thanks for all

All two methods (Malvolio and carr_onstott) works fine, thanks a lot!
I had to modify the header of carr_onstott's method with:
public <T extends Comparable<T>> T search(T node, T root)
because it gives 2 errors, one of wich is that:
D:\UNI\Progetti\MP\1\BTNodeGen.java:191: > expected
    public <T extends Node, Comparable<T>> T search(T node, T root)
                                      ^Why it gives that error?
Thanks to Malvolio I understood what was my fault: in the sons declaration I left "<T>".
In fact with
public BTNodeGen<T> left, right;
it gives no type error and I don't need downcasts.
I always tried to pass in the key value as parameter, but without the correct son's declaration it didn't work.
When I finish to test deeply the entire structure I'll post the results and all the structure's code.
Thank you very much, I was lost without you!

Similar Messages

  • Covariant return types over Generic return types.

    Feeling rather slow on the uptake having only just discovered covariant return types (thanks again cowwoc), I've been looking over one of our soon to be released APIs and think using covariants makes muchos sense for it but there's one issue:
    public interface Foo {
         Foo get();
    public interface Bar {
         Bar get();
    public interface FooBar
              extends Foo, Bar {
         FooBar get();
    }Which isn't allowed, as the compiler states the return types are incompatible (I think incorrectly as it's been further overridden). Its generic equivalent is:
    public interface FooX<T> {
         T get();
    public interface BarX<T> {
         T get();
    public interface FooBarX
              extends FooX<FooBarX>, BarX<FooBarX> {
         FooBarX get();
    }Which works, and well, but the extra hassle of declaring/using generics is turning out to be a pain for our users (this pattern is used extensively). Does anyone have any simple suggestions/recommendations to resolve either the covariant issue or simplify the generics one? Also does anyone have any preferences to which one they prefer (and why)?
    Incidentally does anyone know the the rationale behind not allowing the first example, when clearly it can't be abused (can it)?

    BobDavies wrote:
    . it is because you can not override a method or its definition with the same signatur, which does not include return type.What do you mean "does not include return type"?
    method signature does not count the return type. i think java does allow you to repeat definitions in a sub class but when you put up a different retyrn type, it sees it as an attempt to do overriding, so it flags it out.
    the fact that it works is becuase you are not extending anything but itsself:I am aware of the reasons for the Generic version working, it achieves our aim, I just don't like it when in use. And was wondering why the joining covariants do not work. I still can't see the reason for the FooBar not being allowed when you are allowed to return subtypes. You cannot break the inheritance/return types expectations like this can you? E.g. if I write a bit of code using Foo, it will still work with FooBar, and the same with Bar using FooBar, no? Can you show me an example of why this isn't allowed?your generic version should NOT work either; it is working becuase you are confused:
    public interface FooBarX extends FooX<FooBarX>, BarX<FooBarX> only equals to
    public interface FooBarX extends FooBarX, FooBarX

  • Data Service Auto-Detect Return Type Error

    Hello,
      I am not sure if I am posting in the correct area, as this is my first post in a long time.  I have an error when trying to Auto-Detect Return Type for my Web Service Data Service.  The error is 'Data type "Table_type" cannot be merged with the existing one in package "valueObjects" because the property "ContentID" does not match in case.'  I have configured other return types the exact same way and have tried looking in the documentation for this error as well as searching on the internet.  Any help would be welcomed, Thank You.
    MSP

    Nevermind, I figured it out.  If anyone else has this similar error, it means you have another variable with the exact same name only capitilized in the same return type.

  • JCO Return Type error for BAPI_GOODSMVT_CREATE

    I'm working against a 4.6c instance using the BAPI_GOODSMVT_CREATE to do a 261 movement type.  When running through Xacute, I am getting the attached Return message:
    <RETURN>
    <item>
    <TYPE>E</TYPE>
    <ID>M3</ID>
    <NUMBER>351</NUMBER>
    <MESSAGE>Material not maintained in plant 0066</MESSAGE>
    <LOG_NO />
    <LOG_MSG_NO>000000</LOG_MSG_NO>
    <MESSAGE_V1 />
    <MESSAGE_V2>0066</MESSAGE_V2>
    <MESSAGE_V3 />
    <MESSAGE_V4 />
    <PARAMETER>GOODSMVT_ITEM</PARAMETER>
    <ROW>1</ROW>
    <FIELD />
    <SYSTEM>QAS150</SYSTEM>
    </item>
    </RETURN>
    I know for sure that this item is maintained in this plant as I can perform the 261 through SAP GUI and through ABAP.  Has anyone else run into this problem?  There is an OSS note (570790) for this BAPI, but I think this patch has already been applied.

    Hi Rick - thanks for your quick response.
    I'm fairly confident I have the right config as I can do other BAPIs without any problems.  I did check the material number as well; it is zero padded correctly - again I believe.
    I could be wrong.  I have someone looking into the patch in the OSS note.  Perhaps that is the answer.

  • Return The remote server returned an error: (403) Forbidden error for some file types

    hi
    am using below code to get the byte array 
    byte[] myDataBuffer = client.DownloadData((new Uri(sourceUrl)));
    for source of type .txt/.jpg no problem with accessing.but the file type with .master/.wsp/.cs
    it is returning "The remote server returned an error: (403) Forbidden error for some file types" Error.how can i get rid of this.please help me
    Thanks in Advance

    Hi,
    It seems there is something wrong with your code, from your code the account and key are the same, because their appsetting name are the same.
    string account = ConfigurationManager.AppSettings["StorageAccountName"];
    //string account = CloudConfigurationManager.GetSetting("StorageAccountName");
    //string key = CloudConfigurationManager.GetSetting("StorageAccountAccessKey");
    string key = ConfigurationManager.AppSettings["StorageAccountName"];
    string connectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", account, key);
    return CloudStorageAccount.Parse(connectionString);
    If you use CloudConfigurationManager.GetSetting, please consider set azure project as the startup project, if not, this value will be null, this resulted in solution being started as a web project that didn't run inside the Azure emulator. Since CloudConfigurationManager.GetSetting
    tries to get setting by contacting Azure (or Azure emulator in this case), and it is not running, it returns null.
    Best Regards,
    Jambor
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Error 136 Functions that can be compossed must declare a return type

    Hello,
    I have downloaded the EF Final Release driver and Im working with Oracle 11g express.
    I have the following Procedure:
    PROCEDURE ProductosPedido(
    Datos Out SYS_RefCursor) IS
    BEGIN
    OPEN Datos FOR
    SELECT Nombre,
    TO_NUMBER(Precio * (SELECT SUM(unidades)
    FROM DETALLES_PEDIDO
    WHERE PRODUCTO = PRODUCTO.ID)) Importe
    FROM PRODUCTO;
    END;
    And the following config section:
    <oracle.dataaccess.client>
    <settings>
    <add name="System.Productospedido.RefCursor.Datos" value="implicitRefCursor bindinfo='mode=Output'"/>
    <add name="System.Productospedido.RefCursorMetaData.Datos.Column.0" value="implicitRefCursor metadata='ColumnName=Nombre;BaseColumnName=Nombre;BaseSchemaName=System;BaseTableName=Producto;NativeDataType=nvarchar2;ProviderType=NVarchar2;DataType=System.String;ColumnSize=50;AllowDBNull=true;IsKey=false'" />
    <add name="System.Productospedido.RefCursorMetaData.Datos.Column.1" value="implicitRefCursor metadata='ColumnName=Importe;NativeDataType=number;ProviderType=Decimal;DataType=System.Decimal;AllowDBNull=false;IsKey=false;ColumnSize=8'" />
    </settings>
    </oracle.dataaccess.client>
    I have imported succesfully in my EF Model, but when I try to consume the Procedure it gives me Error 136 Functions that can be compossed must declare a return type
    Any solutions?
    Thanks and best regards!

    A stored procedure does not have a ReturnType, therefore IsComposable="false" and it cannot be used in LINQ queries.
    This limitation is imposed by EF and not by ODP.
    You may want to create a stored function which has a ReturnType ref cursor, and include this stored function into your model. Then, under the same namespace, you create a class with a "stub" method/function and use EdmFunction() to map this stub to the stored function. For example,
    class myFuncClass
    [EdmFunction("Model.Store", "MY_STORED_FUNC_1")]
    public static <your_complex_type_or_DbDataRecord> MyFunc_1(int? column1, ...)
    throw new NotSupportedException("Direct calls are not supported");
    You should be able to call myFuncClass.MyFunc_1(x) in your LINQ query. Your stored function MY_STORED_FUNC_1 will be called in the generated query.

  • Configure return type: There was an error while invoking the operation

    This error only occurs when I pass parameters to Configure return type dialog
    As a follow on from http://forums.adobe.com/message/2663481
    I am getting this in the log.
    !ENTRY com.adobe.flexbuilder.DCDService 4 1 2010-06-15 11:45:29.323
    !MESSAGE Please specify a valid <services/> file path in flex-config.xml.
    !STACK 0
    flex.messaging.config.ConfigurationException: Please specify a valid <services/> file path in flex-config.xml.
        at flex.messaging.config.LocalFileResolver.getConfigurationFile(LocalFileResolver.java:79)
        at flex.messaging.config.AbstractConfigurationParser.parse(AbstractConfigurationParser.java: 67)
        at flex.messaging.config.ServicesDependencies.getClientConfiguration(ServicesDependencies.ja va:150)
        at com.adobe.flexbuilder.dcrad.utils.DCRADUtility.getServiceSettingsOnServer(DCRADUtility.ja va:1398)
        at com.adobe.flexbuilder.dcrad.utils.DCRADUtility.getServerConfiguration(DCRADUtility.java:1 374)
        at com.adobe.flexbuilder.dcrad.views.ServiceExplorerView.refreshService(ServiceExplorerView. java:1703)
        at com.adobe.flexbuilder.dcrad.views.ServiceExplorerView.refreshSelectedServices(ServiceExpl orerView.java:1650)
        at com.adobe.flexbuilder.dcrad.views.internal.actions.ServiceRefreshAction.run(ServiceRefres hAction.java:41)
        at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
        at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionI tem.java:584)
        at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
        at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java :452)
        at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
        at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1003)
        at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3880)
        at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3473)
        at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2405)
        at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2369)
        at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2221)
        at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:500)
        at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
        at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:493)
        at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
        at com.adobe.flexbuilder.standalone.FlexBuilderApplication.start(FlexBuilderApplication.java :109)
        at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:194)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLau ncher.java:110)
        at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.jav a:79)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:368)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1311)
    One problem I keep getting is that FB keeps setting this setting as J2EE Server even when I tell it is standalone. When I add a server an tell FB that it is Remote, does that mean its J2ee?

    Hi,
    This is definitely a Bug. I would have filed it but it would be better if we have the exact steps to reproduce the issue. I am aware that you might not be able to share all your source. But a scaled down example would really be helpful. Please  do log this bug at
    http://bugs.adobe.com/flex/
    Nishad
    Flash Builder Team

  • Behance plugin fails to publish to WIP.  Returns following error: "Failed to upload a WIP update to Behance: Invalid permissions or request type"

    Behance plugin fails to publish to WIP in Lightroom 5.6.  Returns following error: "Failed to upload a WIP update to Behance: Invalid permissions or request type".  (I also saw this question asked in the Deutsche forums in Jan 2014 with no answers)
    In Behance settings Adobe Photoshop Lightroom has permission to:
    Revoke Access
    may act on your behalf to comment, follow users, view and appreciate projects
    Allows access to read network activity feed
    Able to read collections you have marked as private
    Ability to create, manipulate and delete your collections.
    Able to read works in progress marked as private
    Able to post, manipulate and delete a work in progress on your behalf
    Does anyone have a solution?
    -------- System Settings ---------
    Lightroom version: 5.6 [974614]
    Operating system: Windows 8.1 Business Edition
    Version: 6.3 [9600]
    Application architecture: x64
    System architecture: x64
    Logical processor count: 8
    Processor speed: 3.0 GHz
    Built-in memory: 16301.9 MB
    Real memory available to Lightroom: 16301.9 MB
    Real memory used by Lightroom: 374.4 MB (2.2%)
    Virtual memory used by Lightroom: 346.3 MB
    Memory cache size: 224.4 MB
    Maximum thread count used by Camera Raw: 4
    System DPI setting: 96 DPI
    Desktop composition enabled: Yes
    Displays: 1) 2560x1440
    Installed Plugins:
    1) Behance
    2) Canon Tether Plugin
    3) Costco Photo Center
    4) Facebook
    5) Flickr
    6) Leica Tether Plugin
    7) Nikon Tether Plugin
    Config.lua flags: None
    Adapter #1: Vendor : 8086
      Device : 412
      Subsystem : 5b01028
      Revision : 6
      Video Memory : 0
    Adapter #2: Vendor : 10de
      Device : fe4
      Subsystem : 5b01028
      Revision : a1
      Video Memory : 7c1
    Adapter #3: Vendor : 1414
      Device : 8c
      Subsystem : 0
      Revision : 0
      Video Memory : 0
    AudioDeviceIOBlockSize: 1024
    AudioDeviceName: Speakers (Realtek High Definition Audio)
    AudioDeviceNumberOfChannels: 2
    AudioDeviceSampleRate: 44100
    Build: Uninitialized
    CardID: 1042
    Direct2DEnabled: false
    GPUDevice: D3D
    MaxTexture2DSize: 8192
    OGLEnabled: true
    Renderer: Intel(R) HD Graphics 4600
    ShaderModel: 11.1
    Vendor: Intel
    VendorID: 32902
    Version: 8086:0412:5b01028:0006

    Behance Plugin for LR not Authorizing in LR 5.6

  • The return of the "Unexpected Data Type" error

    I've searched the forum and only found discussions of this from over a year ago, so either I'm a loner or this is rearing its ugly head again.
    I've got a project that I've been working on between two machines, both running AE 11.0.2.11 with the same plug-ins. One is a macbook pro, one is a macpro. Both are running 10.6.8 (I believe that's snow leopard). I've been saving the project files and assets to the dropbox folder on my machines so that everything is always in sync between them. ***It's been working flawlessly for months.*** I haven't updated anything recently, other than installing Adobe Acrobat on the desktop machine a few days ago.
    This morning on my desktop machine, I couldn't get the project to open without getting the "unexpected data type" error. Holding down shift did nothing. I instinctively started a new project and imported the .aep I was trying to open. No errors! Then I tried to change work spaces and the error came up again. I hit caps lock and tried again. No go. At one point the workspace drop-down had bullets next to *two* of the workspaces, as if they were both active simultaneously.
    My workaround for the moment was to go to my dropbox on the website and revert to a previously saved version of the same project (thank *YOU* dropbox) from a few days ago. That opened fine, though it's missing a few hours' work.
    My fear is that this will recur and I will have to keep going back in time to keep working (two steps forward, one step back) and I've got a deadline to meet. I will try to stay away from custom workspaces, as one poster to this forum says they are generating that error in CS6 (no helpful replies to that thread).
    Anyone else experiencing this in 2013? Any ideas? All help is much appreciated.
    AE CS6 11.0.2.11
    Mac Pro OS v 10.6.8
    Processor:  2x 2.66ghz dual core intel xeon
    12Gb 667mhz DDR2 RAM

    I just started getting the same error today. Never would've imagined workspaces would have ANYTHING to do with this. But I just went to workspaces and clicked 'reset workspace' for whatever I was on, reloaded the project and no error. WTF Adobe??

  • Incompatible, unrelated return types compile error

    I have:
    public interface ActionControl<C extends ActionControl<C>> extends Control<C>
         public ActionModel getModel();
    public interface ValueControl<V, C extends ValueControl<V, C>> extends Control<C>
         public ValueModel<V> getModel();
    public interface ActionValueControl<V, C extends ActionValueControl<V, C>> extends ActionControl<C>, ValueControl<V, C>
         public ActionValueModel<V> getModel();
    public interface ActionValueModel<V> extends ValueModel<V>, ActionModel
    }The 1.5_04 compiler gives me:
    "ActionValueControl.java:9: types ValueControl<V,C> and ActionControl<C> are incompatible; both define getModel(), but with unrelated return types
    public interface ActionValueControl<V, C extends ActionValueControl<V, C>> extends ActionControl<C>, ValueControl<V, C>"
    The getModel() return types may be unrelated in the super interfaces, but the interface being defined clearly returns a type that satisfies both constraints.
    This works just fine in Eclipse 3.1M2. How can I get this to work with javac?
    Garret

    It turns out that this is a bug. Sun never replied to my bug submission almost two months ago (internal review ID 593682), but from Eclipse compiler bug discussions it appears that the Sun compiler does not comply with JLS3 9.4.1.
    See:
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=122881
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=122617
    Garret

  • Provider-hosted Apps debug error: The remote server returned an error: (401) unauthorised

    Hi,
    Any help appreciated!!
    I'm getting this error: "The remote server returned an error: (401) unauthorised when I debug a provider-hosted app.  I get the error on this line:  
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    See code below
    I created a high trust development environment following the instructions provided here:
    http://msdn.microsoft.com/en-us/library/office/fp179901(v=office.15).aspx and
    http://msdn.microsoft.com/library/office/fp179923
    I created a provider-hosted app with the intent to:
    create a SharePoint list in the appweb
    Use self-signed certificate, tokenhepler.cs and sharepointcontext.cs to retrieve current user context and access on SharePoint.  (No changes were made to tokenhelper.cs and sharepointcontext.cs)
    retrieve list items from the SharePoint list in a button click event handler on a default.aspx of the remote web
    What happens:
    The app is deployed successfully to the Dev site
    The SharePoint feature is deployed and activated
    The default.aspx page of the remote web loads
    The error (see image) is returned on clicking of the button
    My environment is an on-premise SharePoint 2013 with AD and my dev box is standalone windows 8.1 running Visual Studio Professional 2013 Update 3.
    The code block below is a copy of the default.aspx code-behind
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.SharePoint.Client;
    using Microsoft.IdentityModel.S2S.Tokens;
    using System.Net;
    using System.IO;
    using System.Xml;
    using System.Data;
    using System.Xml.Linq;
    using System.Xml.XPath;
    namespace Idea.GeneratorWeb
    public partial class Default : System.Web.UI.Page
    SharePointContextToken contextToken;
    string accessToken;
    Uri sharepointUrl;
    protected void Page_PreInit(object sender, EventArgs e)
    Uri redirectUrl;
    switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
    case RedirectionStatus.Ok:
    return;
    case RedirectionStatus.ShouldRedirect:
    Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
    break;
    case RedirectionStatus.CanNotRedirect:
    Response.Write("An error occurred while processing your request.");
    Response.End();
    break;
    protected void Page_Load(object sender, EventArgs e)
    //// The following code gets the client context and Title property by using TokenHelper.
    //// To access other properties, the app may need to request permissions on the host web.
    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
    //var spContext = new ClientContext("MySPDevInstance");
    //spContext.Credentials = new NetworkCredential("username", "password");
    //using (var clientContext = spContext.CreateUserClientContextForSPHost())
    // clientContext.Load(clientContext.Web, web => web.Title);
    // clientContext.ExecuteQuery();
    // Response.Write(clientContext.Web.Title);
    string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
    if (contextTokenString != null)
    // Get context token
    contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
    // Get access token
    sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
    accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
    // Pass the access token to the button event handler.
    Button1.CommandArgument = accessToken;
    protected void Button1_Click(object sender, EventArgs e)
    // Retrieve the access token that the Page_Load method stored
    // in the button's command argument.
    string accessToken = ((Button)sender).CommandArgument;
    if (IsPostBack)
    sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
    // REST/OData URL section
    string oDataUrl = "/_api/Web/lists/getbytitle('Diagrams In Idea Generator')/items?$select=Title,Diagram,SharingStatus";
    // HTTP Request and Response construction section
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + oDataUrl);
    request.Method = "GET";
    request.Accept = "application/atom+xml";
    request.ContentType = "application/atom+xml;type=entry";
    request.Headers.Add("Authorization", "Bearer " + accessToken);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Response markup parsing section
    XDocument oDataXML = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
    XNamespace atom = "http://www.w3.org/2005/Atom";
    XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
    XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
    List<XElement> entries = oDataXML.Descendants(atom + "entry")
    .Elements(atom + "content")
    .Elements(m + "properties")
    .ToList();
    var entryFieldValues = from entry in entries
    select new
    Character = entry.Element(d + "Title").Value,
    Actor = entry.Element(d + "Diagram").Value,
    CastingStatus = entry.Element(d + "SharingStatus").Value
    GridView1.DataSource = entryFieldValues;
    GridView1.DataBind();
    Any ideas what I might be doing wrong

    Hi ,
    Use the below code
    Public string GetAccessToken(){
    string sharePointSiteUrlHost =  Page.Request["SPHostUrl"].Tostring();
    string AccessToken = tokenHelper.GetS2SAccessTokenWithWindowsIdentity(sharePointSiteUrlHost, Request.LogonUserIdentity);
    return accessToken;
    Than initialize the ClientCOntext with the below Method
     private static ClientContext GetClientContextWithAccessTokenString(string targetUrl, object accessToken)
                ClientContext clientContext = new ClientContext(targetUrl);
                clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
                clientContext.FormDigestHandlingEnabled = false;
                clientContext.ExecutingWebRequest +=
                    delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                        webRequestEventArgs.WebRequestExecutor.WebRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
                        webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                            "Bearer " + accessToken;
                return clientContext;
    use this clientCOntext and it will work.
    Do not use
    SharePointContextProvider
    Whenever you see a reply and if you think is helpful,Vote As Helpful! And whenever you see a reply being an answer to the question of the thread, click Mark As Answer

  • Comparison of references between generics. Missing error/warning?

    If you compare two object references belonging to classes not assignable to each-other either way like this:
    public class SameClassStringBuffer {
        public boolean same (Class c, StringBuffer sb) {
               return c == sb;
    }The sun compiler returns and error saying:
    incomparable types: java.lang.Class and java.lang.StringBuffer
               return c == sb;^
    ... what makes sense.
    Now, if you compare two references with generic types potentially not asignable to each other there is no error. The following compiles with no complains:
    public class Same<X,Y> {
        public boolean same (X a, Y b) {
               return a == b;
    }It it obvious that at runtime that is not an issue cause both are Object type references at that point, yet it is still, in my opinion, an unsafe and bug prone code. Why is there no error or at least a warning message? A case not contemplated by the language steering group? Or am I missing something?
    Thanks.

    But generics is a (probably the) mejor source of warning in java today. The solution is typically a cast and or adding the annotation @SuppressWarning to silence it.
    In this particular case, if there was at least a warning, you would need to cast the references explicitly to something common (Object should always work) and then compare.
    x == (Object)yThe point of the warning is to tell the programmer that what he is doing may cause problems; "you can go ahead but double check if it is really what you want".
    As side note, a warning would have spare me a couple of hours trying to find out what was going on in a piece of code of mine (not as trivial as the example). I'd rather had the "annoying" warning. In any case I think there is little to wonder about the cause of such warning or error as it would just be consistent to the behaviour with specific types. If people still wonders what it means looking at that comparison between (potentially) different typed references I guess they should learn a bit more Java or OO before anything (No offence for anybody intended).

  • Trouble defining an interface return type and parameter

    This is what I have so far
    interface Display {
       //Excel
       public HSSFRow createRow(HSSFSheet sheet);
       public HSSFWorkbook createContainer();
       //Pdf
       public Document createContainer(Document document);
       public Document createRow(Document document);
    }Really what I want is one method declaration called createRow() that has an unknown return type and an unknown input parameter type. Is there a way to accomplish this? I will have two classes implement this interface. An Excel class and a PDF class. Those two classes will contain the correct implementations of createContainer() and createRow().
    For example my Excel class will contain this
    public HSSFRow createContainer(){
    return new HSSFWorkbook();
    }and my pdf class will look something like this
    public Document createContainer(Document document){
    return new Document();
    }My main class then can do something like this:
    Display display;
    if(input.equals("xls")){
    display = new Excel();
    }else if(input.equals("pdf")){
    display = new Pdf();
    //Here I can call the correct method to build the outer container
    display.createContainer();What I'm trying to do is have reuse all my algorithms and just have generic calls to create the main container, rows, etc.I had a previous post on this but have created a new one thats more specific to interfaces because ideally I'd like use interfaces here if possible, but not if it will get more complicated than its worth.

    What generic things do you wish to be able to do with all documents? Whatever those things are, they are what should be defined in either an interface or abstract class.
    Here is an example (without any error checking), though it's not the only approach you could take:
    public interface ForumKidDocument {
         public void nextRow();
         public void addTableCell(String cellContent);
         public void save(File file);
         // add whatever other methods you want all documents to be able to do
    public class ExcelForumKidDocument implements ForumKidDocument {
         private HSSFWorkbook workbook;
         private HSSFSheet worksheet;
         private HSSFRow currentRow;
         private int row;
         private int col;
         public XLSForumKidDocument() {
              this.workbook = new HSSFWorkbook();
              this.worksheet = workbook.createSheet();
         public void nextRow() {
              this.currentRow = this.worksheet.createRow(row++);     
              col = 0;
         public void addTableCell(String cellContent) {
              HSSFCell cell = currentRow.createCell(col++);
              cell.setCellValue(cellContent);
         public void save(File file) {
              //TODO:  save workbook to the given File
    public class PDFForumKidDocument implements ForumKidDocument {
    }Then in your outer method, you work with ForumKidDocument instances, calling only ForumKidDocument methods, without having to know anything about the inner workings of the document type.

  • Guideline for deciding method return type

    Hi All,
    I have some concerns in deciding the return type of some specific methods in the application (web service application to be specific).
    Concern: There are methods like 'deleteData', 'cancelProcess', 'uploadData' etc. Ideally these methods don't require server to perform complex business logic. Now there are 2 views to decide the return type of these methods. The first approach could be to return a boolean indicating whether the operation is successful or not and the other apporach is to return void but throw an exception if anything goes wrong.
    Both approaches have their own advantages and drawbacks. Sending a boolean seems to be cleaner but in case of unsuccess caller won't get the exact exception but just a flag. In second apporach, the caller has to rely on try/catch to decide the logical flow.
    I know, there can't be any generic answer to this question but I just wanted to know comments from experts on this or probably some guidelines.
    Thanks and Regards,
    Ashish Arya

    If there is a legitimate reason why your method might not actually do what it should, then use the boolean return value.
    Example: someList.remove("foo") will return false if "foo" is not actually in the list (because remove() simply specifies that it will make sure that the element is not in the list after the call. Since this is fulfilled in this case, there's no case to throw an exception, even if it didn't actually remove anything).
    If the only reason for not doing what it should is some error condition, then throw an exception:
    Example: someList.get(100) will throw an exception, when the list has less than 101 elements.

  • The remote server returned an error: (503) Server Unavailable In SharePoint 2010.

    I created a web app with claims based authentication ,
    basiclly i follwe this blog
    http://donalconlon.wordpress.com/2010/02/23/configuring-forms-base-authentication-for-sharepoint-2010-using-iis7/
    but when i login it throws 503 error
    Server Error in '/' Application.
    The remote server returned an error: (503) Server Unavailable.
    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.Net.WebException: The remote server returned an error: (503) Server Unavailable.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [WebException: The remote server returned an error: (503) Server Unavailable.]
    System.Net.HttpWebRequest.GetResponse() +1126
    System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +81
    [ServerTooBusyException: The HTTP service located at http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc is too busy. ]
    System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10258154
    System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +539
    Microsoft.IdentityModel.Protocols.WSTrust.IWSTrustContract.Issue(Message message) +0
    Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr) +61
    Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst) +36
    Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo) +26062081
    Microsoft.SharePoint.SPSecurityContext.SecurityTokenForLegacyLogin() +270
    Microsoft.SharePoint.IdentityModel.SPWindowsClaimsAuthenticationHttpModule.GetSecurityTokenFromWindowsIdentity(WindowsIdentity windowsIdentity, HttpContext httpContext) +21
    Microsoft.SharePoint.IdentityModel.SPWindowsClaimsAuthenticationHttpModule.AuthenticateRequest(Object sender, EventArgs e) +1176
    System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
    any thoughts?
    thanks in advance!
    Share Knowledge and Spread Love!

    Hi ,
    I was also facing the same issue on changing my credentials. This effects the ServiceTokenApplicationPool and other pools related to the Web applications
    To resolve this  follow these :
    1. Open IIS Manager , under Connection section you can see the Name of your site collection(as
    siteCollectionName(Username))
    2. Open SiteCollection , select Application Pools. A new window with your Web application pool names would open.
    3. Right click on web app, select Advance Setting... , under Process Model select Identity 
    4. check for Custom account , click set and enter your Credentials and click
    OK
    Atlast Refresh the IIS manager.
    Thank you.
    Under application pools Do select the ServiceTokenApplicationPool  also and follow steps 3 and 4

Maybe you are looking for

  • Problem with ASA 5505

    Good morning, I'm having the following problem. I configured a ASA 5505 with VPN and a VPN Remote Access Site-to-site. Everything is working, but when I reload the ASA does not work anymore VPNs, Remote Access error 412 and the Site-to-site does not

  • Photo album: Play button not functioning on slide show

    In order to learn this album construction, I've begun by just copying the files from the demo (http://labs.adobe.com/technologies/spry/demos/gallery_pe/dynamic/index.html), renaming the paths and throwing in some new images. BUT, the Play button does

  • What is "please contact iTunes support to complete transaction"

    Hi all , please I need your help I need to buy something it says "please contact iTunes support to complete transaction" - how I can fix that? Or how I contact iTunes support .

  • IiPhoto 11 Red-eye Reduction too black

    Hey there! I recently bought a new iMac and when I transferred my stuff over from my precious Mac, it told me I had to update to iPhoto 11. I did that, but I prefer my previous version of iPhoto (?08)... The red-eye reduction never seems to have the

  • Why system alarm sound when opening an app on my MBP 13"?

    Recently started to hear system alarm sound when opening an app., eg. Mail, Safari (usually from the Dock). No apparent operational problem, but quite annoying, especially since I don't know why. Happens on my 13" MBP, but not on my iMac, both runnin