Showing posts with label .Net. Show all posts
Showing posts with label .Net. Show all posts

5/15/2009

Silverlight: A few notes on HTML / JavaScript access from Silverlight

 

You can call into a Silverlight control from JavaScript in the HTML page and access Silverlight managed code properties and methods. The process is relatively straight forward really lets you use a Silverlight object as a true control, and not just a fancy animated advertisement (Sorry Flash designers…)

I will follow shortly with notes on the other half of the picture, accessing HTML objects and JavaScript functions from Silverlight code.

 

 

Accessing data / method in Silverlight from JavaScript

Step 1:  Add a reference

Add a reference to System.Windows.Browser, and add a using or Imports to your code file.

        using System.Windows.Browser;

 

Step2: Mark the item or class to be scriptable

The item can be either a property or a method. The attribute is [ScriptableMember] (<ScriptableMember> in VB.Net). Some examples show [ScriptableMemberAttribute], but the short form is preferred.

A sample property:

        private int x=9;

        [ScriptableMember]
        public int MyProperty { get { return x; } set { x = value; } }

 

The entire class can be marked as Scriptable using [ScriptableType], but note that all public members are then available for access from JavaScript.

See notes at the end of this article for more info on the use of the attributes.

 

Example:

or the entire class (warning: all publics are exposed)
[ScriptableType]
public class Calculator2
{
    public int Add(int a, int b)
       { return a + b; }

    public int Subtract(int a, int b)
    { return a – b; }
}

 

Step 3: Register the class as scriptable

Register the class as scriptable either in the app.xaml.cs, but more likely in yourpage.xaml.cs file.

Example if registered from Page.xaml

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            HtmlPage.RegisterScriptableObject("Page", this);

        }

Example to register another class:

         private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            HtmlPage.RegisterScriptableObject("MyPage",  new Class1());

        }

 

Step 4: Make the call from the HTML page:

This example makes the call from a button, but could also be done from the <BODY> onload event or the Siverlight control’s load event.

    <script>
    function GetSomeData() {
        sl = document.getElementById("Xaml1");
        alert(sl.Content.Page.MyProperty);
     }
    </script>
    <button onclick="GetSomeData()" >Get Data</button>

or as a single line:
        <button onclick="sl = document.getElementById('Xaml1');alert(sl.Content.Page.MyProperty);" >Get Data 2</button>

or even...
        <button value="Get Data" onclick="alert(document.getElementById('Xaml1').Content.Page.MyProperty);" >Get Data 2</button>

 

Some observations and discoveries…

  • Both attributes are not needed!
    Some sources say that both the class must be marked as [ScriptableType] and the property or method must be marked as [ScriptableMember]. I found that just marking the class as [ScriptableType] made all public members script accessible. I also found that marking a property or method as [ScriptableMember] was all that was needed to expose the one member. It was not necessary to mark up the class at all.

    And I would say that Microsoft agrees with me!  ;-)
    http://msdn.microsoft.com/en-us/library/system.windows.browser.scriptabletypeattribute(VS.95).aspx
  • “ScriptableTypeAttribute Class - Indicates that all public properties, methods, and events on a managed type are available to JavaScript code when they are registered by using the RegisterCreateableType method.”

    “If you want to expose only a subset of properties, methods, and events as scriptable endpoints, do not use a ScriptableTypeAttribute object. Instead, attribute the subset of properties, methods, and events with a ScriptableMemberAttribute object.”

    If you do choose to use [ScriptableType] and want to hide one of the public members mark it with:

       [ScriptableMember(EnableCreateableTypes = false)]

    Note: the preferred notation for the attributes excludes the word “Attribute”, so use [ScriptableType] and [ScriptableMember].

     

  • "HtmlAccess=Enabled" is not needed for calls INTO Silverlight, only to enable calls out.
      <asp:Silverlight ID="Xaml1" HtmlAccess=Enabled ...

 

Useful web resources:

3/14/2009

SharePoint: Finding SharePoint GUIDs

 

Update… I put together a PowerShell version of this here: http://techtrainingnotes.blogspot.com/2011/06/finding-sharepoint-guids-using.html  (so now you have four versions!)

Update… I put together a version of this that uses the SharePoint web services so you can get the GUIDs without having to be on the server. The EXE and the C# project can be downloaded here.

So now you have three versions, API from a Windows app, API from a LAYOUTs page and Web Services from a Windows app.

---

 

 

Just a little code to share….   :-)

 

I needed a quick way to find the GUIDs used on a SharePoint site so I wrote a little C# routine to display them. Below is the sample code for both a Windows app and a SharePoint Layouts ASPX page.

 

The Windows Version:

As this calls the API instead of the web services so this will need to be run from one of the SharePoint servers.

Add a textbox, a button and a listbox on a form then…

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {  InitializeComponent();    }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox1.Text = listBox1.SelectedItem.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            SPSite site;
            try
            {
                site = new SPSite(txtSiteURL.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            listBox1.Items.Add("Site: " + site.ID.ToString());
            SPWeb web = SPContext.Current.Web;  //site.RootWeb;
            listBox1.Items.Add("Web: " + web.ID.ToString());
            foreach (SPList list in web.Lists)
            {
                listBox1.Items.Add(list.Title + ": " + list.ID.ToString());
            }

        }

    }
}

 

The Layouts folder version:

Create a text file in the SharePoint LAYOUTS folder with a name like “getGuids.aspx” and paste the following code. Run the page from any site:  http://youserver/yoursite/_layouts/getGuids.aspx

<%@ Page Language="C#"  %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    private void Page_Load(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        SPSite site;
        site = SPContext.Current.Site;
        ListBox1.Items.Add("Site: " + site.ID.ToString());
        SPWeb web = SPContext.Current.Web;   // site.RootWeb;
        ListBox1.Items.Add("Web: " + web.ID.ToString());
        foreach (SPList list in web.Lists)
        {
            ListBox1.Items.Add(list.Title + ": " + list.ID.ToString());
        }
    }

    private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        TextBox1.Text = Request.Form["ListBox1"];
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Width="530px" />
        <br /><br />
        Click to copy to the text box.<br />
        <asp:ListBox ID="ListBox1" runat="server"
          OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
          Rows="20" AutoPostBack="True"/></div>
    </form>
</body>
</html>

1/18/2009

ASP.NET State Management Comparison



The following is a chart that I often use in ASP.Net classes to compare State Management options.
Where?What?Who can seeLife spanIssuesNew inNotes
Cookies
Request.Cookies
Response.Cookies
User's browser or diskstringscurrent usercurrent browser session or set expire datelimited data size (typically 4096 bytes), cookie limit (typically 20 per site)user can disableancient history!  
Hidden HTML fieldsbrowserstringscurrent userone page postback (one round trip)limited to text and visible as Page Source textancient history! Easy to hack!
Applicationweb server RAM (1)objectsall sessionsuntil server is restartedlimited by RAMClassic ASP 
Sessionweb server RAM (1)objectscurrent userend of user's session (Session.Abandon or timeout [default 20 minutes])limited by RAMClassic ASP 
ViewStatehidden INPUT in pageobjectscurrent userone page postback (one round trip)bandwidth and slower page load <i>and</i> post timesASP.Net 1.0Can be disabled by the developer (per page, web.config or code)
ControlStatein ViewStateobjectscurrent userone page postback (one round trip)Not as simple to use as ViewStateASP.Net 2.0Cannot be disabled by the developer using the control
Cache (2)web server RAMobjectsall sessionsUntil:
- Expires
- a dependency changes
- RAM is needed
You must always check to see if the object still exists as cached items are both automatically deleted and are deleted when RAM runs low. ASP.Net 1.0Can be used as an Application object that can expire

 

(1) State can be stored in local server RAM (InProc), another server's RAM (StateServer), SQL Server (SQLServer) or a custom destination. For any option other than InProc all objects must be serializable.

(2) Cache is not usually mentioned in lists of state options, but is nearly identical to Application with the addition of expiration.



12/08/2007

Which Conference or Event to Attend in 2008?

Too many choices! So little time and money... DevConnections? April 20-23 Orlando, FL 5 shows in 1! SharePoint Connections, ASP.Net Connections, SQL Server Connections, Architect Connections, Visual Studio & .Net Connections. http://www.devconnections.com/ Microsoft Office System developer conference? Feb 10-13 2008 San Jose, California https://microsoft.crgevents.com/ODC2008/ SharePoint Conference 2008 March 2-6 Seattle, Washington http://mssharepointconference.com Can't decide between Office Developer Conference 2008 vs. SharePoint Conference 2008? Check out this SharePoint Product Group blog SharePoint Information Worker Conference 2008 Feb 2-6 Nashville, TN http://sharepointsolutions.com/sharepoint-conferences/sharepoint-conference.html TechEd 2008 Orlando, FL Oh No! There are two of them this year! Tech·Ed U.S. 2008 Developers June 3-6, 2008 Tech·Ed U.S. IT Professionals June 10-13, 2008 http://www.microsoft.com/events/teched2007/default.mspx Microsoft Office Visio Conference 2008 Feburary 5-6 Redmond, WA http://www.msvisioconference.com/

8/02/2007

.Net Links - web resources

Some of the links I have collected for .Net - no particular order or grouping...

Why things were changed between 1.1 and 2.0 (very interesting blog) http://weblogs.asp.net/scottgu/archive/2005/08/21/423201.aspx

New in 3.0 http://download.microsoft.com/download/5/8/6/5868081c-68aa-40de-9a45-a3803d8134b8/csharp_3.0_specification.doc http://msdn2.microsoft.com/en-us/vstudio/aa700830.aspx http://msdn.microsoft.com/data/ref/linq/

.Net history (video) http://channel9.msdn.com/ShowPost.aspx?PostID=44084 http://channel9.msdn.com/ShowPost.aspx?PostID=44940

Dot Net Security Whitepaper: Improving Web Application Security: Threats and Countermeasures http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp

Spelling checker add-in for Visual Studio 2005 http://weblogs.asp.net/scottgu/archive/2006/04/18/Spell-Checker-Plug_2D00_in-for-VS-2005-for-ASP.NET-and-HTML-Pages.aspx

2.0 Generics overview: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/csharp_generics.asp

IIS Lockdown Tool http://www.microsoft.com/technet/security/tools/locktool.mspx

"Security Smack Down" http://www.devcity.net/PrintArticle.aspx?ArticleID=50

Defend Your Code with Top Ten Security Tips Every Developer Must Know http://msdn.microsoft.com/msdnmag/issues/02/09/SecurityTips/default.aspx

ASP.NET Security Overview http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q306590

Ajax / Atlas article: http://msdn.microsoft.com/msdnmag/issues/06/07/AtlasAtLast/

Want to see what's in the ViewState collection? Go to this link and search for "ViewState decoder" http://pluralsight.com/blogs/fritz/archive/2004/07/01/472.aspx

Other languages for dotnet! (I count nearly 50, some with multiple sources) http://www.dotnetpowered.com/languages.aspx

Web Parts tutorial http://www.ondotnet.com/pub/a/dotnet/2005/05/23/webparts_1.html

Tutorial: Developing a templated control designer in ASP.NET 2.0 http://blogs.infosupport.com/wouterv/archive/2005/09/15/Developing-a-templated-control-designer-in-ASP.NET-2.0-_2800_5-parts_2900_.aspx

How to store the web part catalog in an XML file http://www.carlosag.net/Articles/WebParts/catalogPartSample.aspx Application Blocks, patterns and practices http://msdn.microsoft.com/practices/

2003 -> 2005 issues / solutions... Visual Studio 2005 Web Application Projects (Released May 8, 2006) http://msdn.microsoft.com/asp.net/reference/infrastructure/wap/default.aspx Update to the Web Project Conversion Wizard The Web Project Conversion Wizard in Visual Studio 2005 has been updated to handle newly discovered conversion issues. http://www.microsoft.com/downloads/details.aspx?familyid=7cecd652-fc04-4ef8-a28a-25c5006677d8&displaylang=en Upgrade from ASP.NET 1.x info http://msdn.microsoft.com/asp.net/reference/migration/upgrade/default.aspx

Memory in .NET - what goes where http://www.yoda.arachsys.com/csharp/memory.html ASP.NET 2.0 Security Practices at a Glance http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/PAGPractices0001.asp Newsgroups: (can be searched at http://groups.google.com) microsoft.public.dotnet microsoft.public.dotnet.academic.* microsoft.public.dotnet.csharp.general microsoft.public.dotnet.datatools microsoft.public.dotnet.distributed_apps microsoft.public.dotnet.faqs microsoft.public.dotnet.framework.* microsoft.public.dotnet.general microsoft.public.dotnet.internationalization microsoft.public.dotnet.jscript.general microsoft.public.dotnet.languages.* microsoft.public.dotnet.myservices microsoft.public.dotnet.samples microsoft.public.dotnet.scripting microsoft.public.dotnet.security microsoft.public.dotnet.vb.general microsoft.public.dotnet.vjsharp microsoft.public.dotnet.vsa microsoft.public.dotnet.xml Google Newsgroup searches list of all MS dotnet groups: http://groups.google.com/groups/dir?q=microsoft.public.dotnet start of a top level search: http://groups.google.com/groups?&as_ugroup=microsoft.public.dotnet.*

General Sites: Microsoft .NET http://www.microsoft.com/net/ DotNetSlackers: ASP.NET News For Lazy Developers http://www.dotnetslackers.com/ DotNetJunkies.com - Tutorials, news, sample code, user contributed code and web services directory http://www.dotnetjunkies.com/ GotDotNet: The Microsoft .NET Framework Community http://www.gotdotnet.com/ ASP.NET http://www.asp.net/ .NET Rocks! is a weekly Internet audio talk show for .NET Developers. http://www.dotnetrocks.com/ MSDN: ASP.NET - ASP and ASP.NET 2.0, as well at Atlas and Visual Web Developer http://msdn.microsoft.com/asp.net/ ASP.NET QuickStart Tutorials http://samples.gotdotnet.com/quickstart/aspplus/ 411 ASP.NET Directory http://www.411asp.net/ ASP.NET.4GuysFromRolla.com http://aspnet.4guysfromrolla.com/ 123aspx.com ASP.NET Resource Directory http://www.123aspx.com/

SQL Injection http://www.spidynamics.com/whitepapers/WhitepaperSQLInjection.pdf http://www.spidynamics.com/whitepapers/Blind_SQLInjection.pdf http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html and more... http://www.google.com/search?hl=en&q=sql+injection+white+paper

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.