Loading...

Sunday, March 10, 2013

How To Deploy Custom List Forms With Data Form Webpart?

To Deploy list instances along with Custom New/Edit/Display Form, You can follow these steps
1)In SharePoint Designer
 Select  List and Librararies --->Preview Custom Forms in Browser-->Edit this Page in browser
 and export the DataForm Webpart

2)Edit the .Webpart file in Visual studio to remove  parameters for WebUrl (ctrl F +search for Weburl and remove it)
replace all occurrence of ListID to ListName and the Guid with the Name Of the List
and save .webpart file
In Webpart Properties remove ListName Property

3)Upload this Deployable Datformwebpart and Edit the Custom List Pages to Add this new Webpart
 and Remove the existing one.
In Visual Studio, Create the Module under ListInstance folder to provision Custom Form
(You can get this module from exported wsp to Visual studio of required site template which is saved as wsp)
Open the elements.xml file of the module and replace the CData of Dataform Webpart obtained in step 2
(If you need additional help , pls drop a comment)

4)Now to Deploy with ListInstance Follow the steps given here

After reading this artical I found that, Dataform Webpart will not work as it depends on List Guids

Also Check this url, which dynamically replaces tokens with Guids and custom pages are the sites pages

Create an Item in an External List on the Server

1)While creating ListItem in an external List
you must have visited this msdn How to

2)Have you come across this error for Authenticated users?
Failed to create a list item for this external list based on the Entity (External Content Type) 'ECT' in EntityNamespace '/sites/test space'. Details: Credentials were not found for the current user within the target application 'ECT'. Please set the credentials for the current user.

3)Edit the external Content Type,and make sure in Connection properties ,Authentication mode is selected to 'BDC Identity'

Thursday, February 28, 2013

SPLong Operations VS Wait Modal Poup

1) If you need to show the wait  screen when the list of activities being executed in behind the scenes
  SPLong Operation is pretty good solution.

2) In the scenarios  Where Client Object Model is used in huge,Following source will definitely help you


<script type="text/javascript">

function RedirectTo() 
{
  window.location = "New Page Url";      
  
}

function showWaitScreen() 
{
  
window.parent.eval("SP.UI.ModalDialog.showWaitScreenWithNoClose('Please Wait', 'Redirecting to new page...', 76, 330);");
  setTimeout(RedirectTo, 1500);
}
  
ExecuteOrDelayUntilScriptLoaded(showWaitScreen, "sp.js");
        
 </script>

Questions and Comments are welcome !!!

Tuesday, January 1, 2013

Linqpad To Query Office 365 Odata REST connection(ListData.svc)

1)Download the Linqpad @
2)Install SPClient from here
3)Add required dlls And Import namespaces  as follows
In Linqpad,Ribbon-->Query-->Queryfeatuters

In Query window (Of Linqpad) ,Select C# Program  to execute this source code, when prompted for input enter values as shown in Switch case
(Modify _spUrl variable to your SharePoint online site)

void Main()
{
    while (true) 
    {
        var result = LINQPad.Util.ReadLine("command:");
        switch (result)
        {
            case "auth":
                Office365.Auth(Config.spUrl);
            break;
            case "getlists":
                GetLists();
            break;
            case "getlistitems":
                GetListItems();
            break;
            case "getschema":
                GetSchema();
            break;
            case "createpopulatelist":
                CreatePopulateList();
            break;
            case "odata":
                OData();
            break;
        }
    }
}
class Config 
{
    public static string spUrl { get {
        if(_spUrl == "")
            _spUrl = Util.ReadLine("spUrl:");
        return _spUrl;
    } set {
        _spUrl = value;
    } }
    private static string _spUrl = "https://swaticloud.sharepoint.com";
}
void OData()
{
    var wc = new System.Net.WebClient();
    wc.Headers.Add("Cookie", CookieMonster.DoInternetGetCookieEx(Config.spUrl).GetCookieHeader(new Uri(Config.spUrl)));
    wc.DownloadString(Config.spUrl + "/_vti_bin/listdata.svc").Dump();
}
// // via: [Using the SharePoint Foundation 2010 Managed Client Object Model](http://msdn.microsoft.com/en-us/library/ee857094.aspx)
static ClientContext GetContext()
{
    var context = new ClientContext(Config.spUrl);
    context.Credentials = CredentialCache.DefaultCredentials;
    context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(delegate(object sender, WebRequestEventArgs e){
        e.WebRequestExecutor.WebRequest.CookieContainer = CookieMonster.DoInternetGetCookieEx(Config.spUrl);
    });
    return context;
}
void GetLists()
{
    var context = GetContext();
    var results = context.LoadQuery(context.Web.Lists.Include(list => list.Title, list => list.Id));
    context.ExecuteQuery();
    results.ToList().ForEach(x => {
        x.Title.Dump();
    }); 
}
void GetListItems()
{
    var context = GetContext();
    var list = context.Web.Lists.GetByTitle("Contact");
    var camlQuery = new CamlQuery();
    //camlQuery.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='Category'/><Value Type='Text'>Development</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>";
    camlQuery.ViewXml = @"<View />";
    var listItems = list.GetItems(camlQuery);
    context.Load(listItems);
    //context.Load(listItems, items =>  items.Include(
    //  item => item["Name"]
    //));
    context.ExecuteQuery();
    listItems.ToList().ForEach(x => {
        Console.WriteLine(x["Name"]);
    });
}
void GetSchema()
{
    var context = GetContext();
    var list = context.Web.Lists.GetByTitle("Contact");
    context.Load(list);
    var fields = list.Fields;
    context.Load(fields);
    context.ExecuteQuery();
    fields.ToList().ForEach(f => {
        var e = XElement.Parse(f.SchemaXml);
        if((string)e.Attribute("FromBaseType") != "TRUE") 
        {
            e.Attributes("ID").Remove();
            e.Attributes("SourceID").Remove();
            e.Attributes("ColName").Remove();
            e.Attributes("RowOrdinal").Remove();
            e.Attributes("StaticName").Remove();
            Console.WriteLine(e);
        }
    });
}
void CreatePopulateList()
{
    ClientContext clientContext = GetContext();
    Web site = clientContext.Web;

    // Create a list.
    ListCreationInformation listCreationInfo = new ListCreationInformation();
    listCreationInfo.Title = "Client API Test List";
    listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
    List list = site.Lists.Add(listCreationInfo);

    // Add fields to the list.
    Field field1 = list.Fields.AddFieldAsXml(@"
        <Field Type='Choice' DisplayName='Category' Format='Dropdown'>
            <Default>Specification</Default>
            <CHOICES>
              <CHOICE>Specification</CHOICE>
              <CHOICE>Development</CHOICE>
              <CHOICE>Test</CHOICE>
              <CHOICE>Documentation</CHOICE>
            </CHOICES>
        </Field>
        ", true, AddFieldOptions.DefaultValue);
    Field field2 = list.Fields.AddFieldAsXml(@"
        <Field Type='Number' DisplayName='Estimate'/>
        ", true, AddFieldOptions.DefaultValue);

    // Add some data.
    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
    ListItem listItem = list.AddItem(itemCreateInfo);
    listItem["Title"] = "Write specs for user interface.";
    listItem["Category"] = "Specification";
    listItem["Estimate"] = "20";
    listItem.Update();

    listItem = list.AddItem(itemCreateInfo);
    listItem["Title"] = "Develop proof-of-concept.";
    listItem["Category"] = "Development";
    listItem["Estimate"] = "42";
    listItem.Update();

    listItem = list.AddItem(itemCreateInfo);
    listItem["Title"] = "Write test plan for user interface.";
    listItem["Category"] = "Test";
    listItem["Estimate"] = "16";
    listItem.Update();

    listItem = list.AddItem(itemCreateInfo);
    listItem["Title"] = "Validate SharePoint interaction.";
    listItem["Category"] = "Test";
    listItem["Estimate"] = "18";
    listItem.Update();

    listItem = list.AddItem(itemCreateInfo);
    listItem["Title"] = "Develop user interface.";
    listItem["Category"] = "Development";
    listItem["Estimate"] = "18";
    listItem.Update();

    clientContext.ExecuteQuery();
}
class Office365 
{
    public static void Auth(string url) 
    {
        app app = new app();
        Thread.Sleep(2000);
        app.w.Dispatcher.BeginInvoke(new Action(delegate(){
            var dp = new System.Windows.Controls.DockPanel { LastChildFill = true };
            var wb = new System.Windows.Controls.WebBrowser();
            System.Windows.Controls.DockPanel.SetDock(wb, System.Windows.Controls.Dock.Top);
            dp.Children.Add(wb);
            app.w.Content = dp;
            wb.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(delegate(object sender, System.Windows.Navigation.NavigationEventArgs e){
                //Console.WriteLine(CookieMonster.DoInternetGetCookieEx(Config.spUrl).GetCookieHeader(new Uri(Config.spUrl)));
            });
            wb.Navigate(url);
        }));
    }
    public class app 
    {
        public System.Windows.Application a;
        public System.Windows.Window w;
        public app() 
        {
            ThreadStart myThreadDelegate = new ThreadStart(this.Start);
            Thread myThread = new Thread(myThreadDelegate);
            myThread.SetApartmentState(ApartmentState.STA);
            myThread.Start();
        }
        public void Start() 
        {
            a = new System.Windows.Application();
            w = new System.Windows.Navigation.NavigationWindow();
            a.MainWindow = w;
            a.MainWindow.Show();
            a.Run();
        }
    }
}


class CookieMonster
{
    [DllImport("wininet.dll", EntryPoint = "InternetGetCookieExW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
    static extern bool InternetGetCookieEx([In] string Url, [In] string cookieName, [Out] StringBuilder cookieData, [In, Out] ref uint pchCookieData, uint flags, IntPtr reserved); 
    public static CookieContainer DoInternetGetCookieEx(string url)
    {
        var cookies = new CookieContainer();
        var cookieData = new StringBuilder();
        uint dataSize = 0;
        uint INTERNET_COOKIE_HTTPONLY = 0x00002000;
        var hresult1 = InternetGetCookieEx(url, null, cookieData, ref dataSize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero);
        cookieData = new StringBuilder((int)dataSize);
        var hresult2 = InternetGetCookieEx(url, null, cookieData, ref dataSize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero);
        //if (!hresult2)
        //  throw new Win32Exception(Marshal.GetLastWin32Error());
        if (cookieData.Length > 0)
            cookies.SetCookies(new Uri(url), cookieData.ToString().Replace(';', ','));
        return cookies;
    }
    [DllImport("ieframe.dll", SetLastError = true)]
    public static extern int IEGetProtectedModeCookie([In] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpszURL, [In] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpszCookieName, [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder pszCookieData, ref uint pcchCookieData, uint dwFlags );
    // HRESULT IEGetProtectedModeCookie(LPCWSTR lpszURL, LPCWSTR lpszCookieName, LPWSTR pszCookieData, DWORD *pcchCookieData, DWORD dwFlags );
    public static CookieContainer DoIEGetProtectedModeCookie(string url)
    {
        var cookies = new CookieContainer();
        var cookieData = new StringBuilder();
        uint datasize = 0;
        uint INTERNET_COOKIE_HTTPONLY = 0x00002000;
        var hresult1 = IEGetProtectedModeCookie(url, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY);
        cookieData = new StringBuilder((int)datasize);
        var hresult2 = IEGetProtectedModeCookie(url, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY);
        //if (hresult2 != 0)
        //  throw new Win32Exception(Marshal.GetLastWin32Error());
        cookieData.Dump();
        if (cookieData.Length > 0)
            cookies.SetCookies(new Uri(url), cookieData.ToString().Replace(';', ','));
        return cookies;
    }
}

Monday, December 24, 2012

How to add Taxonomy Fields To Page Layouts?

1)Create Site Column Of Type Manged Metadata and add this Site Column to Associated Page Layout Content type
For example
If Page Layout is associated  with Project Page,Edit Site columns to include this Manage Metadata columns

2)In SPD refresh toolbox  ,So that Managed Metadata field is visible  as shown in image, Drag this  field to PageLayout
Add taxonomy reference

<%@ Register Tagprefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

This field will be visible only when you create New Page using this Page Layout


Sunday, December 23, 2012

Importing Very Simple BDC Model

1)Create a SQL table in Sql DB 
2)Create New  External Content Type in SPD with SQL connection  with User's Identity as Authentication mode.
3)Create required operation like read, write for Table Created in SQL
4)In CA,In Secure Store Service , Create Target application which maps the Credentials for External Content Type (If necessary)
5)In BCS Service Application, Set the required permissions for External Content Type
6)Create The External List With this Content Type
When You browse the list , you come across to this exception
“Login failed for user “NT AUTHORITY\ANONYMOUS LOGON” while browsing to external list.”
To avoid this enable RevertToSelf Authentication Mode as described here
Now ,Set the Authentication Mode to BDC Identity.
7)Save the ECT and export this Model

8)Edit the .bdcm file and modify it according to production server as follows.Save  this file and Import this model in  Production server CA
 <LobSystemInstance Name="UserInfocon">
          <Properties>
            <Property Name="ShowInSearchUI" Type="System.String"></Property>
            <Property Name="AuthenticationMode" Type="System.String">RevertToSelf</Property>
            <Property Name="DatabaseAccessProvider" Type="System.String">SqlServer</Property>
            <Property Name="RdbConnection Data Source" Type="System.String">ProdServer</Property>
            <Property Name="RdbConnection Initial Catalog" Type="System.String">DataBaseName</Property>
            <Property Name="RdbConnection Integrated Security" Type="System.String">SSPI</Property>
            <Property Name="RdbConnection Pooling" Type="System.String">true</Property>
          </Properties>
        </LobSystemInstance>

Sunday, December 9, 2012

Silverlight Client Object Model For Windows Phone

In SharePoint 2010,Silverlight Client Object Model was not supported for Windows Phone
But This is improved in SharePoint 2013
As Windows Phone 7.5 first creates an object of the Authenticator class or ODataAuthenticator
which were added to the SharePoint 2013 client object model for Microsoft Silverlight for Windows Phone. It then uses this object as the user’s credentials.
Read more in this msdn post