Friday, April 29, 2011

Write A Facebook App In JavaScript

As an hobby I wrote a game in JavaScript and would love to publish it to Facebook, can you write a Facebook application using pure HTML and JavaScript?

From stackoverflow
  • Yes, though your app may not be able to do much on Facebook. Have a look at http://developers.facebook.com for documentation.

  • Yes. Absolutely. In fact, one of the options for developing a Facebook application is an embedded frame pointing to your website which can be whatever you want, including straight HTML web serving.

    There are two officially sanctioned libraries for accessing Facebook information and one of them is Javascript based.

    You can do quite a bit on Facebook with just Javascript/HTML. There's a lot of possibilities using services outside of your own site (think Flckr, Google Ajax API etc...)

    Facebook applications are pleasantly simple to develop.

    The documentation is indeed at: http://developers.facebook.com/

    I would also note that traffic with regards to Facebook, things can spin up really quickly. There are stories of students creating applications which quickly scaled to millions of users. I'm not saying this is likely to be the case for you, but it is can be an effective and a highly viral distribution platform.

    Dustin Fineout : The link to the story of students "creating applications which quickly scaled to millions of users" is broken. Any chance you can find another link or the text of the article? Would like to read it...

ASP.NET Login page

I want to add login for registered users in my website. How shall I proceed with it? Is it through the use of sessions? What will happen to the Session variable once the logout happens??

From stackoverflow
  • You should use the provided Login control and Membership system.

    About Session vars, nothing special will happen. ASP.NET forms authentication does not use SessionState by default.

    Roshan : I dont want to use the Login Control.
    Mehrdad Afshari : Then you can use the underlying membership APIs: http://msdn.microsoft.com/en-us/library/yh26yfzy(loband).aspx
  • I'd take a look a related questions, such as

    http://stackoverflow.com/questions/592364/login-membership-net

    This topic is already covered quite a lot on SO.

    Session state and log in are somewhat orthogonal. You have a session regardless of whether or not you are logged in.

  • I would recommend using forms authentication with perhaps a custom backend using IIdentity and IPrincipal. There’s lots of information available how to do this but I think this link forms a good starting point http://msdn.microsoft.com/en-us/library/aa480476.aspx

  • Your question is extremely broad and there are many different ways that you can implement what is, in effect, a "membership" system for an ASP.NET website.

    I would suggest that you start by reading the "Introduction to Membership" article from MSDN. This article will give you an overview of how ASP.NET membership works in the most "standard" way.

    It also mentions using the various ASP.NET membership "controls" (Login, LoginView, LoginStatus & PasswordRecovery for example).

    Using these controls along with the built-in ASP.NET membership providers (for example, ASP.NET provides a SQL membership provider to work against SQL Server as the data store for your user accounts and credentials) will allow you to implement a complete membership and authentication system with virtually no code at all (i.e. all the functionality is provided by the built-in "membership" controls and declarative mark-up).

    Finally, a really good series of articles on this subject is:

    Examining ASP.NET 2.0's Membership, Roles, and Profile

    from the 4guysfromrolla site. It's starts at the very beginning of the membership topic and goes right the way through to touching on the implementation of a custom membership provider and administrative interface for managing user credentials to round out the whole subject.

Communication between the EDT and main threads in JAVA

Hello,

I have been asking a lot of questions about a project I have been working on recently. Here is the scenario I am in and any help or point in the right direction would help a lot...

This is a network program built with a server and multiple clients. Each client has a GUI which must act according to commands sent from the server. Each client is wrapped within a class called Player. This Player has a GUI (extends JFrame) and a main method, and the Server has a main method only (no GUI). At first, this class was created in the main thread like this:

EventQueue.invokeLater(new Runnable()
{
    public void run()
    {
        new Player().setVisible(true);
    }
 });

This was working fine, until I realized that the entire Player class was now executing in the EDT. So, when I wait for commands from the server the entire GUI locks up until that command is sent and proper actions are executed. As you can imagine, this is a horrible design and proved to be a real pain of a coding environment when everytime you want to check for something you must find some crazy work around so that the GUI still remains in tact.

Obviously, I must check for the commands from the Server in a separate thread and run the GUI components in the EDT. My second implementation had two classes - one for the GUI and one for the Player. The idea was that the Player had a variable that held the GUI so that I could access the GUI from the Player class, something like this:

class Player
{
    public GUI gui;

    ...

    // And then start this gui inside of the EDT.
    EventQueue.invokeLater(new Runnable()
    {
         public void run()
         {
              this.gui = new GUI().setVisible(true);
         }
    }

This doesn't work either, because "this" inside of the new Runnable object refers to the Runnable object, not the Player.

So, I don't know how to communicate between the Player class in one thread and the corresponding GUI class in the EDT thread.

Any help?

From stackoverflow
  • Instead of using an anonymous inner class, why not just declare a class the implements Runnable and have a constructor that takes a GUI instance as argument?

    Also, if your GUI class is not thread safe, consider using a message queue to communicate between the EDT & main thread.

  • To handle your problem with the this pointer, you should write:

    class Player
    {
        public GUI gui;
    
        ...
    
        // And then start this gui inside of the EDT.
        EventQueue.invokeLater(new Runnable()
        {
             public void run()
             {
                  Playser.this.gui = new GUI().setVisible(true);
             }
        }
    }
    
  • You may try this:

    class Player { public GUI gui;

    ...
    
    // And then start this gui inside of the EDT.
    EventQueue.invokeLater(new Runnable()
    {
         public void run()
         {
              Player.this.gui = new GUI().setVisible(true);
         }
    }
    
  • Boris Pavlović gets the syntax right (actually you could just remove the this.), but still the code doesn't make sense. The gui field is initialised sometime after the Runnable event is queued, so it is unsafe for the player thread to use it.

    You could construct Player on the EDT (but do the network operations off EDT). Or register the GUI as a listener (observer) of the Player. invokeAndWait would work, but is dangerous as it often leads to the occasional difficult-to-debug deadlock.

  • "until I realized that the entire Player class was now executing in the EDT"

    The constructor occurs on the EDT but methods called on this class might not be.

    You should construct the player GUI as you originally intended.

     EventQueue.invokeLater(new Runnable() 
     {
        public void run()
        {
            new Player().setVisible(true);
        }
     });
    

    But Player can launch a separate thread in the constructor (personally I'd share a connection between the Players).

    Of course, the callback methods from the server should use invokeLater() when modifying visible components.

VB.NET Me.Close() doesn't work, the form doesn't close??

Hi all,

The form is an About Us form so has nothing on it only a text box and a OK button.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Me.Close()
End Sub

Here is how I'm opening the form:

Private Sub AboutAppStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutAppStripMenuItem.Click
    Dim formAbout As New FormAbout()
    formAbout.Show()
End Sub

Why won't the button close the form? I'm puzzled, I tried another button just in case with the same result.

UPDATE: I set a break point on Me.Close() and it isn't reaching it when I click the button, I created a new button and the same thing happened.

Thanks

From stackoverflow
  • From MSDN:

    Showing the control is equivalent to setting the Visible property to true. After the Show method is called, the Visible property returns a value of true until the Hide method is called.

    Philip Wallace : Spineless downvoters who don't back it up with a comment why...
  • I am betting the event handler for the button1_click event has been inadvertently removed.

    Try double-clicking on the button in design time and see if it pulls you back to that same exact piece of code - or a new event handler definition.

    If it's a new event handler definition - copy your code there and delete the first one.

    There are other ways to manually add the event handler in the designer's code-behind - but maybe that's for a later progression.

    From within VS click the "Show all files" button in solutions explorer. Grab us the code in .Designer.vb and paste it in here and we'll nail it down for you definitively.

    Here's mine:

    
        Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Partial Class Form1
        Inherits System.Windows.Forms.Form
    
        'Form overrides dispose to clean up the component list.
         _
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            Try
                If disposing AndAlso components IsNot Nothing Then
                    components.Dispose()
                End If
            Finally
                MyBase.Dispose(disposing)
            End Try
        End Sub
    
        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer
    
        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
         _
        Private Sub InitializeComponent()
            Me.Button1 = New System.Windows.Forms.Button
            Me.SuspendLayout()
            '
            'Button1
            '
            Me.Button1.Location = New System.Drawing.Point(131, 91)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(133, 50)
            Me.Button1.TabIndex = 0
            Me.Button1.Text = "Button1"
            Me.Button1.UseVisualStyleBackColor = True
            '
            'Form1
            '
            Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
            Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
            Me.ClientSize = New System.Drawing.Size(292, 266)
            Me.Controls.Add(Me.Button1)
            Me.Name = "Form1"
            Me.Text = "Form1"
            Me.ResumeLayout(False)
    
        End Sub
        Friend WithEvents Button1 As System.Windows.Forms.Button
    
    End Class
    
    Fredou : handle keyword is in question above
  • when formabout is open

    click on pause(break all) button in visual studio

    click on step into in debug in visual studio

    click on the close button in formabout

    you will see which code is executed, if any

    * edit *

    another question

    is formabout.enabled property is true?

  • I tested the following

    Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button1.Click
        Dim f As New Form2
        f.Show()
    End Sub
    End Class
    
    
    Public Class Form2
    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button1.Click
        Me.Close()
    End Sub
    End Class
    

    and did not have problems. As was suggested, re-create your button and code.

Larger integer to smaller unsigned type conversion in C

I was goint through k & r. I was having problem in understanding following lines on page 197(section A6)

Integral conversions: any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.

Can any body explain this in a bit detail. Thanks

From stackoverflow
  • It means only low value bits will be count and high order bits will be discarded.

    For example:

    01111111 11111111 11110000 00001111
    

    when converted to a 16 bit unsigned short will be:

    11110000 00001111
    

    This is effectively mathematically expressed in:

    target_value = value % (target_type_max+1)           ( % = modulus operator )
    
  • any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.

    Let's take this bit by bit and from backwards:

    What is the largest value that can be represented in the unsigned type of width n bits?

    2^(n) - 1.
    

    What is one more than this value?

    2^n.
    

    How does the conversion take place?

    unsigned_val = signed_val % 2^n
    

    Now, the why part: The standard does not mandate what bit representation is used. Hence the jargon. In a two's complement representation -- which is by far the most commonly used -- this conversion does not change the bit pattern (unless there is a a truncation, of course).

    Refer to Integral Conversions from the Standard for further details.

WPF TextBlock highlight certan parts based on search condition

Hello,

I have TextBlock that has Inlines dynamicly added to it (basically bunch of Run objects that are either italic or bold).

In my application I have search function.

I want to be able to highlight TextBlock's text that is in being searched for.

By highlighting I mean changing certain parts of TextBlock text's color (keeping in mind that it may highlight several different Run objects at a time).

I have tried this example http://blogs.microsoft.co.il/blogs/tamir/archive/2008/05/12/search-and-highlight-any-text-on-wpf-rendered-page.aspx

But it seams very unstable :(

Is there easy way to solve this problem?

From stackoverflow
  • Ended up writing following code

    At moment has few bugs, but solves the problem

                if (Main.IsFullTextSearch)
            {
                for (int i = 0; i < runs.Count; i++)
                {
                    if (runs[i] is Run)
                    {
                        Run originalRun = (Run)runs[i];
    
                        if (Main.SearchCondition != null && originalRun.Text.ToLower().Contains(Main.SearchCondition.ToLower()))
                        {
                            int pos = originalRun.Text.ToLower().IndexOf(Main.SearchCondition.ToLower());
    
                            if (pos > 0)
                            {
                                Run preRun = CloneRun(originalRun);
                                Run postRun = CloneRun(originalRun);
    
                                preRun.Text = originalRun.Text.Substring(0, pos);
                                postRun.Text = originalRun.Text.Substring(pos + Main.SearchCondition.Length);
    
                                if (i - 1 < 0)
                                    runs.Insert(0, preRun);
                                else
                                    runs.Insert(i - 1, preRun);
    
                                runs.Insert(i + 1, new Run(" "));
                                runs.Insert(i + 2, postRun);
    
                                originalRun.Text = originalRun.Text.Substring(pos, Main.SearchCondition.Length);
    
                                SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);
                                originalRun.Background = brush;
    
                                i = i + 3;
                            }
                        }
                    }
                }
            }
    
  • Can you please provide the full code. Because i am not getting any CloneRun method. Thanks in advance.

SetValue on PropertyInfo instance error "Object does not match target type" c#

Been using a Copy method with this code in it in various places in previous projects (to deal with objects that have same named properties but do not derive from a common base class or implement a common interface).

New place of work, new codebase - now it's failing at the SetValue with "Object does not match target type" even on very simple examples... and it worked last week....

    public static void Copy(object fromObj, object toObj)
    {   
        Type fromObjectType = fromObj.GetType();
        Type toObjectType = toObj.GetType();

        foreach (System.Reflection.PropertyInfo fromProperty in 
            fromObjectType.GetProperties())
        {
            if (fromProperty.CanRead)
            {
                string propertyName = fromProperty.Name;
                Type propertyType = fromProperty.PropertyType;

                System.Reflection.PropertyInfo toProperty = 
                    toObjectType.GetProperty(propertyName);

                Type toPropertyType = toProperty.PropertyType;

                if (toProperty != null && toProperty.CanWrite)
                {
                    object fromValue = fromProperty.GetValue(fromObj,null);
                    toProperty.SetValue(toProperty,fromValue,null);
                }
            }
        }
    }

    private class test
    {
        private int val;
        private string desc;

        public int Val { get { return val; } set { val = value; } }

        public string Desc { get { return desc; } set { desc = value; } }

    }

    private void TestIt()
    {
        test testo = new test();
        testo.Val = 2;
        testo.Desc = "TWO";

        test g = new test();

        Copy(testo,g);

    }

Hopefully someone can point out where I am being daft???

From stackoverflow
  • Try:

    toProperty.SetValue(toObj,fromValue,null);
    

    You are trying to pass in the property (toProperty) as the target object, instead of toObj. For info, if you are doing lots of this, maybe consider HyperDescriptor, which can vastly reduce the reflection cost.

    kpollock : D'oh! that's the bug I fixed the LAST time I wrote it - and forgot to check this time...
  • Take a look at AutoMapper

  • Should be

    toProperty.SetValue(toObj,fromValue,null);
    
    Peter Lillevold : Too slow I guess..
  • Try this: http://sandrino.be/2009/03/copy-all-the-properties-of-an-object-in-c/

    kpollock : looks the same as mine with more compact syntax (though the if check is redundant). I prefer to be able to stick breakpoints in/examine return values from functions, hence the wordiness of mine...
  • this is good but this thing fails whenever you use the vanilla classes.