pdanan

See also: Other Geeks@INDC
Cara menyembunyikan kolom di Sharepoint Form

1. PowerShell . Ref: http://howtosharepoint.blogspot.com/2010/11/hide-columns-in-sharepoint-new-edit-and.html

2. Programmatically, dengan membuat custom form di ascx/aspx

3. Content Type, dengan cara seting kolom sebagai Hidden.

4. jQuery.  Contoh :

<script type="text/javascript">
$(document).ready(function() {
    $('nobr:contains("Completion time")').closest('tr').hide();
});
</script>
Share this post: | | | |
Error di Webpart Page: No item exists at http:// …/mywebpartpage.aspx?id=999. It may have been deleted or renamed by another user

Error No item exists at http:// … /mywebpartpage.aspx?id=999. It may have been deleted or renamed by another user

yang terjadi di webpart page dimana disitu ada webpart/visual webpart yang kita bangun,

dikarenakan konflik pemakaian parameter id. Karena itu jangan memakai parameter id di webpart/visualwebpart yang kita bangun, karena parameter itu dipakai oleh sistem  Sharepoint. Selain id ada beberapa

parameter yang di-reserve oleh Sharepoint, selengkapnya adalah :

  • FeatureId
  • ListTemplate
  • List
  • ID
  • VersionNo
  • ContentTypeId
  • RootFolder
  • View
  • FolderCTID
  • Mode
  • Type
  • PageVersion
  • IsDlg
  • Title
  • _V3List_

Reference : http://blogs.technet.com/b/stefan_gossner/archive/2009/01/30/querystring-parameters-you-should-not-use-in-your-sharepoint-application.aspx

Share this post: | | | |
Posted: Nov 14 2011, 02:05 PM by pdanan | with no comments
Filed under:
​Dua Cara membuat WCF Client di Sharepoint page

Dua Cara membuat WCF Client di Sharepoint page :

1. Seting binding dan endpoint disimpan di web.config :

Caranya seperti yang biasa dilakukan yaitu dengan melalui Add Service Reference. Setelah itu Seting binding dan Endpoint yang ada di app.config (dibagian dalam <system.serviceModel> ) copy-kan ke web.config (juga dibagian dalam <system.serviceModel> ) . Keuntungan cara ini adalah bila diperlukan perubahan seting binding atau endpoint tinggal mengedit file config-nya. Kerugiannya kalau banyak webservice yang berarti banyak seting yang harus ditambah di web.config. Supaya tidak terlalu banyak baris, seting binding dan endpoint bisa disederhanakan dengan menghapus yang tidak perlu, sebagai contoh:

    <system.serviceModel>

        <bindings>

            <basicHttpBinding>

                <binding name="WebService1Soap" ></binding>

            </basicHttpBinding>

        </bindings>

        <client>

            <endpoint address="http://192.168.1.23/services/mysvc.asmx"

                binding="basicHttpBinding" bindingConfiguration="WebService1Soap"

                contract="TarkService.WebService1Soap" name="WebService1Soap" />

        </client>

    </system.serviceModel>

2. Seting binding dan endpoint dideklarasikan di code :

Keuntungan dan Kerugian cara ini adalah lawan dari cara 1) yaitu kerugiannya untuk merubah seting binding dan endpoint harus merubah code dan keuntungannya tidak perlu merubah web.config.

Langkah-langkahnya:

1.    Buat Proxy dengan svcutil.exe yang ada di visual studio 2010 Command Prompt. By default dia akan membuat file config yang berisi seting binding dan endpoint, karena kita ingin seting binding dan endpoint ada di code sehingga tidak diperlukan file config, maka bisa kita beri opsi /noconfig supaya tidak membuat file config.

Contoh : SvcUtil http://192.168.1.23/services/mysvc.asmx /out:C:\SvcProxy.cs /noconfig

 

2.    Selanjutnya lakukan deklarasi binding dan endpoint, dan akses webservice di code.

Contoh :

BasicHttpBinding Binding = new BasicHttpBinding();

EndpointAddress endpointAddress = new EndpointAddress("http://192.168.1.23/services/mysvc.asmx");

WebService1SoapClient oWebSvc = new WebService1SoapClient(Binding, endpointAddress);

       int itemID = 999999;

       string teks= trk.GetText(itemID).InnerXml;

Sumber : Buku Programming WCF Services oleh  Juval Lowy

Share this post: | | | |
Posted: Nov 10 2011, 10:13 PM by pdanan | with no comments
Filed under: ,
Excel REST Services - Cara gampang menampilkan isi file Excel di tempat lain

Katakan kita punya file Excel yang ada chartnya, Chartnya mau kita share ke orang lain.

File Excel tsb ada di site internal, sedangkan kita mau Chartnya ada di publishing site atau home page supaya mudah dilihat orang lain.

Atau kita mau tampilkan Chart tersebut di file Word yang ada di local computer kita.

Solusi gampangnya, pakai Excel REST Services.

REST kurang lebih seperti web services untuk mengambil data luar dengan tinggal memanggil URL addressnya.

 

Untuk contoh tadi,

Katakan file excelnya di http://contoso/Shared%20Documents/Clock.xlsx .

Maka untuk mengakses Chart yang namanya Clock juga , tinggal mengakses URL address sbb: http://contoso/_vti_bin/ExcelRest.aspx/Shared%20Documents/Clock.xlsx/Model/Charts('Clock') . Lalu tempelkan URL di tempat yang kita mau.

Gambaran lengkapnya ada di : http://blogs.office.com/b/microsoft-excel/archive/2009/11/09/excel-services-in-sharepoint-2010-rest-api-examples.aspx .

 

Variasi lain, kita juga bisa melakukan perubahan nilai terhadap apa yang ditampilkan URL tadi, namun perubahan itu bersifat local, tidak mempengaruhi file Excel aslinya, bahkan tidak mempengaruhi session lain yang sama-sama mengakses data (Excell Services memang ditujukan untuk multi akses jadi tidak perlu kuatir jika diakses bareng dalam waktu bersamaan).

 

Yang perlu diingat, permission dari file tersebut tetap dibawa, jadi hanya user yang punya permission terhadap file Excel nya yang bisa mengakses.

 

Referensi:

http://blogs.office.com/b/microsoft-excel/archive/2009/11/05/excel-services-in-sharepoint-2010-rest-api-syntax.aspx

http://blogs.msdn.com/b/cumgranosalis/archive/tags/rest/

Share this post: | | | |
Word Automation Services untuk urusan convert file word

Di sharepoint server sudah ada Word Automation Services untuk urusan convert file word,

 

Berikut supporting format nya :

 

Source:

• Word 97-2003 Document (DOC) and Word 97-2003 Template (DOT)

• Rich Text Format (RTF)

• Single File Web Page (MHTML)

• HTML

• Word 2003 XML

• Word 2007/2010 XML

 

Destination:

• PDF

• XPS

• Office Open XML (DOCX, DOCM)

• Word 97-2003 Document (DOC)

• Rich Text Format (RTF)

• Single File Web Page (MHTML)

• Word 2007/2010 XML

 

Dan berikut referensi untuk penerapannya:

 

http://msdn.microsoft.com/en-us/library/ff742315.aspx

http://pholpar.wordpress.com/2011/10/27/using-sharepoint-2010-word-automation-services-to-convert-document-synchronously/

http://www.sharepointkings.com/2011/05/word-automation-services-part-1.html

 

Share this post: | | | |
Membuat Sharepoint Custom Form dari UserControl dengan cara FormTemplates di Visual Studio 2010

Membuat Sharepoint Custom Form dari UserControl dengan cara FormTemplates di Visual Studio 2010 :

1. Create Empty project

2. Add Content Type:

2.a. Set Inherits="FALSE"

2.b. Tambahkan Field-fieldnya. Perlu diperhatikan:
- Bila fieldnya LOOKUP, buat juga ListDefinition+ListInstance LOOKUPnya di Project tsb ! (Kalau tidak begitu field Lookupnya pasti kehilangan relasi!).
Contohnya ada di http://blogs.claritycon.com/blog/2011/05/27/provisioning-a-sharepoint-2010-lookup-column-with-caml/
- Bila fieldnya Managed Metadata maka tambahkan seperti cara disini : http://www.sharepointconfig.com/2011/03/the-complete-guide-to-provisioning-sharepoint-2010-managed-metadata-fields/ (di Link tsb ada Source Code yang bisa diunduh sbg pedoman juga). Yang perlu diingat kalau pakai field managed metadata Scope Feature nya harus Site kalau tidak akan Error 'object reference not set to an instance of an object' ketika aktivasi Features pas proses Deploy.

2.c. Setelah ContentType bisa dideploy, lanjutkan dengan langkah untuk menempelkan custom form, yaitu menambahkan elemen FormTemplates, sbg contoh:
    <XmlDocuments>
      <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
        <FormTemplates  xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
          <Edit>id_CustomForm</Edit>
        </FormTemplates>
      </XmlDocument>
    </XmlDocuments>

3. Berikutnya membuat custom Formnya, Buat Sharepoint Mapped ke folder ControlTemplates. Buat usercontrol sbg contoh: CustomForm1.ascx.

4. Di CustomForm1.ascx , Tambahkan:
<%@ Register TagPrefix="wssuc" TagName="ToolBar" src="~/_controltemplates/ToolBar.ascx" mce_src="~/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="~/_controltemplates/ToolBarButton.ascx" mce_src="~/_controltemplates/ToolBarButton.ascx" %>

5. Copy Paste Sharepoint Rendering Template yang diperlukan dari file DefaultTemplates.ascx yang ada di folder ControlTemplates.
- Untuk List copy yang <SharePoint:RenderingTemplate id="ListForm" runat="server">.

- Untuk Document Library, copy yang <SharePoint:RenderingTemplate id="DocumentLibraryForm" runat="server">, perlu diperhatikan didalam situ ada link ke Template "DocumentLibraryFormCore", untuk itu delete saja ini: <SharePoint:FormComponent TemplateName="DocumentLibraryFormCore" runat="server"/> dan gantikan dengan isi dari <SharePoint:RenderingTemplate id="DocumentLibraryFormCore" runat="server">.

Kemudian di RenderingTemplate, edit id-nya sesuai dengan yang di deklarasi contenttypenya, sebagai contoh disini :
<SharePoint:RenderingTemplate id="id_CustomForm" runat="server">.

Setelah itu bisa coba dideploy, hasilnya form-nya masih seperti bawaan, karena kita belum melakukan kustomisasi form.

6. Selanjutnya kita mulai kustomisasi form. Katakanlah kita akan kustom field-fieldnya. Untuk itu langkah2 sbb:

- Delete bagian yang merender Field, untuk List adalah : <SharePoint:ListFieldIterator runat="server"/> dan untuk DocumentLibrary adalah : <SharePoint:DocumentLibraryFields ID="DocumentLibraryFields1" runat="server"/>

- Selanjutnya kita tambahkan field-field nya.

Setelah <SharePoint:FormToolBar ID="FormToolBar1" runat="server"/>, tambahkan sbb :

<table class="ms-formtable" style="margin-top: 8px;" border="0" cellpadding="0" id="formTbl" cellspacing="0" width="100%">
<SharePoint:ItemValidationFailedMessage ID="ItemValidationFailedMessage1" runat="server"/>
<SharePoint:ChangeContentType ID="ChangeContentType1" runat="server"/>
<%-- <SharePoint:DocumentLibraryFields ID="DocumentLibraryFields1" runat="server"/> --%>
        <tr>
            <td width="190px" valign="top" class="ms-formlabel">
                <h3 class="ms-standardheader">
                    <nobr>Name<span class="ms-formvalidation"> *</span></nobr>
                </h3>
            </td>
            <td width="400px" valign="top" class="ms-formbody">
                <SharePoint:FormField runat="server" ID="FormField1" ControlMode="Edit" FieldName="Name" />
                <SharePoint:FieldDescription runat="server" ID="FieldDescription1" FieldName="Name"
                    ControlMode="Edit" />
            </td>
        </tr>

        <tr>
            <td width="190px" valign="top" class="ms-formlabel">
                <h3 class="ms-standardheader">
                    <nobr>Title</nobr>
                </h3>
            </td>
            <td width="400px" valign="top" class="ms-formbody">
                <SharePoint:FormField runat="server" ID="FormField2" ControlMode="Edit" FieldName="Title" />
                <SharePoint:FieldDescription runat="server" ID="FieldDescription2" FieldName="Title"
                    ControlMode="Edit" />
            </td>
        </tr>

        <tr>
            <td width="190px" valign="top" class="ms-formlabel">
                <h3 class="ms-standardheader">
                    <nobr>Ukuran</nobr>
                </h3>
            </td>
            <td width="400px" valign="top" class="ms-formbody">
                <SharePoint:FormField runat="server" ID="FormField3" ControlMode="Edit" FieldName="Ukuran" />
                <SharePoint:FieldDescription runat="server" ID="FieldDescription3" FieldName="Ukuran"
                    ControlMode="Edit" />
            </td>
        </tr>
 <SharePoint:ApprovalStatus ID="ApprovalStatus1" runat="server"/>
</table>

7. Setelah itu bisa dideploy ContentTypenya dan dicoba dengan mengaplikasikannya di DocumentLibrary.
Yang perlu diketahui dari kustomisasi field tsb adalah tiap Field2 itu ada atribut ControlMode, yang bisa disesuaikan, misal spy Fieldnya tidak bisa diedit kita ubah jadi ControlMode="Display". Dan tentu saja kita bisa tambahkan logic2 disitu, atau di code-behind.

Terimakasih untuk yang membuat referensi2 dibawah ini:
- Untuk Add Lookup Column di ContentType: http://blogs.claritycon.com/blog/2011/05/27/provisioning-a-sharepoint-2010-lookup-column-with-caml/
- Untuk Add Managed Metadata Column di ContentType http://www.sharepointconfig.com/2011/03/the-complete-guide-to-provisioning-sharepoint-2010-managed-metadata-fields/
- Untuk membuat Custom Form : http://customformtemplates.codeplex.com/ dan http://sharepointbox.blogspot.com/2010/11/how-to-use-custom-form-templates-in.html
- Untuk referensi cara lain membuat custom form dengan FormUrls : http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=223431&av=333251 (disini dibahas juga tentang cara FormTemplates spt kita bahas) dan di Ebook Sharepoint 2010 as a Development Platform , hal 1027. Selain itu ada juga cara lain seperti di http://spcustomlistformdemo.codeplex.com/

Share this post: | | | |
Bind List items to SPGridView

 

SPGridView Bind to List items :

At File *.aspx :

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

<SharePoint:SPGridView runat="server" ID="gridView"  AutoGenerateColumns="false" /> 

</asp:Content>

 

At File *.aspx.cs :

 

protected void Page_Load(object sender, EventArgs e)

{

    SPWeb myWeb = SPContext.Current.Web;

    SPList myList = myWeb.Lists.TryGetList("myList");

    if (!Page.IsPostBack)

    {

        BindToGrid(myList, gridView);

    }

}

 

private void BindToGrid(SPList myList, SPGridView grdView)

{

    SPListItemCollection results = myList.Items;

    grdView.AutoGenerateColumns = false;

    grdView.DataSource = results.GetDataTable();

    // create the bound fields

    SPBoundField boundField;

    boundField = new SPBoundField();

    boundField.HeaderText = "Title";

    boundField.DataField = "Title";

    grdView.Columns.Add(boundField);

    boundField = new SPBoundField();

    boundField.HeaderText = "Created";

    boundField.DataField = "Created";

    grdView.Columns.Add(boundField);

    grdView.DataBind(); 

}

 

Share this post: | | | |
Posted: Jul 08 2011, 08:55 PM by pdanan | with no comments |
Filed under: ,
Better way to get List Object in Sharepoint 2010

In Sharepoint 2010, there is new method to get List object, that is TryGetList. With TryGetList you don't bother to "try catch" to check the existence.

Sample :

SPList mylist = web.Lists.TryGetList("shared documents");

if (mylist != null)

{

    MessageBox.Show(mylist.Title + " is exist");

}

Reference:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistcollection.trygetlist.aspx

Share this post: | | | |
Better Way to Check if File is Exist

Better Way to Check if File is Exist

If you check existing file using Exists property in SPFile , You better get it from SPWeb.GetFile and not from SPFolder.Files because it is ‘cleaner’ ( Not throws Exception). 

BAD Way ( will Throws Exception if File Not Exist ):

SPFile ofile = myLib.RootFolder.SubFolders["mysubfolder"].Files["myfilename"];

if (ofile.Exists)

    // File is exist ..

 

BETTER Way  :

SPFile ofile = web.GetFile(web.ServerRelativeUrl + @"/MyLibName/MySubFolder/myfilename.ext");

if (ofile.Exists)

    // File is exist ..

 

Share this post: | | | |
Posted: Apr 14 2011, 08:59 PM by pdanan | with no comments
Filed under:
Get Thumbnail and Preview File from Picture Library Programmatically

 

Get Thumbnail and Preview File from Picture Library Programmatically:

Get Thumbnail File:

string urlthumbnail = oitem["EncodedAbsThumbnailUrl"].ToString();

SPFile filethumbnail = olist.RootFolder.SubFolders["_t"].Files[urlthumbnail];

 

Get Preview File:

string urlpreview = urlthumbnail.Replace("_t", "_w");

SPFile filepreview = olist.RootFolder.SubFolders["_w"].Files[urlpreview];

 

Share this post: | | | |
Posted: Apr 09 2011, 09:56 PM by pdanan | with no comments
Filed under:
Create video thumbnail automatically in Asset Library by utilizing ffmpeg that run by event receiver

 Create automatic video thumbnail in Asset Library.

In Asset Library, there is 'Preview Image URL' Field, that you can use to show thumbnail of video files. But How if you want it to automatically filled in, so you don't bother to create thumbnail manually, put it in the picture library, and fill the 'Preview Image URL' field with the picture URL. Here I want to share about how we can do it utilizing Ffmpeg tool.

Here is the steps:

1. Prepare ffmpeg.exe, make use it can use to create thumbnail from video files, and put it in certain folder. Let say, it is "C:\ffmpeg\ffmpeg.exe".

2. Create Temporary folder to put the video file that ready to process by ffmpeg in. Let say, it is:  "C:\TempVideo".

3. Create picture library as container for thumbnail files, let say it's name is "ThumbPics".

5. Create event receiver solution in VisualStudio 2010,  with event receiver type is "List Item Events", event source is "Asset Library", and the events are "Item was Added", "Item was Updated", and "Item is being Deleted".

Note: If you want install event receiver only to specific specific asset library, you can use the technique that I've writen before : http://geeks.netindonesia.net/blogs/pdanan/archive/2011/04/05/install-event-receiver-to-specific-existing-list-content-type.aspx

6. Make sure only Video Content Type or Custom Content Type that inherited from Video Content Type in the Asset Library that event receiver will be applied to. Or If you want to mix with others kind of content type besides Video Content Type, then you should modify the code below to include filtering/validating added file.

And here is the source code:

private string workingpath = @"C:\TempVideo";

private string ffexepath = @"C:\ffmpeg\ffmpeg.exe";

private string ThumbPiclibName = "ThumbPics";

/// <summary>

/// An item was added.

/// </summary>

public override void ItemAdded(SPItemEventProperties properties)

{

    base.ItemAdded(properties);

    if (properties.ListItem.FileSystemObjectType == SPFileSystemObjectType.File)     //Make sure if it is file (not folder)

         CreateThumbnail(properties);

 

}

 

/// <summary>

/// An item was updated.

/// </summary>

public override void ItemUpdated(SPItemEventProperties properties)

{

    base.ItemUpdated(properties);

    if (properties.ListItem.FileSystemObjectType == SPFileSystemObjectType.File)     //Make sure if it is file (not folder)

        CreateThumbnail(properties);

}

 

public override void ItemDeleting(SPItemEventProperties properties)

{

    base.ItemDeleting(properties);

     if (properties.ListItem.FileSystemObjectType != SPFileSystemObjectType.File)     //Make sure if it is file (not folder)

        return;

    SPListItem oitem = properties.ListItem;

    SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];

    SPUserToken privilegedToken = privilegedAccount.UserToken;

    using (SPSite osite = new SPSite(properties.Web.Url, privilegedToken))

    {

        using (SPWeb oweb = osite.OpenWeb())

        {

            SPFieldUrlValue TumbField = new SPFieldUrlValue(oitem["Preview Image URL"].ToString());

            SPFile TumbFile = oweb.GetFile(TumbField.Url);

            if (TumbFile.Exists)

            {

                if (TumbFile.CheckOutType != SPFile.SPCheckOutType.None)

                    TumbFile.CheckIn(string.Empty);

                TumbFile.Delete();   

            }

        }

    }

}

 

private void CreateThumbnail(SPItemEventProperties properties)

{

    SPList olist = properties.List;

    SPListItem oitem = properties.ListItem;

    SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];

    SPUserToken privilegedToken = privilegedAccount.UserToken;

    using (SPSite osite = new SPSite(properties.Web.Url, privilegedToken))

    {

        using (SPWeb oweb = osite.OpenWeb())

        {

            string thumbnailURL = string.Empty;

            SPFile filevideo = properties.ListItem.File;

            string filevideopath = Path.Combine(workingpath, filevideo.Name);

            string thumbname = filevideo.Name + ".jpg";

            string thumbpath = Path.Combine(workingpath, thumbname);

 

            // Download file to local folder (c:TempVideo):

            byte[] binFile = filevideo.OpenBinary();

            if (binFile.Length > 0)

            {

                FileStream fs = new FileStream(filevideopath, FileMode.OpenOrCreate, FileAccess.Write);

                fs.Write(binFile, 0, binFile.Length);

                fs.Close();

                fs.Dispose();

            }

            if ((File.Exists(filevideopath)) && (File.Exists(ffexepath)))

            {

                // Create file thumbnail using ffmpeg:

                string Params = string.Format("-i \"{0}\" \"{1}\" -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", filevideopath, thumbpath, 1);

                RunProcess(ffexepath, Params, 5000);

 

                if (File.Exists(thumbpath))

                {

                    //insert file thumbnail to Picture Library (ThumbPics):

                    SPList Thumbfolder = oweb.Lists[ThumbPiclibName];

                    FileStream fStream = File.OpenRead(thumbpath);

                    byte[] contents = new byte[fStream.Length];

                    fStream.Read(contents, 0, (int)fStream.Length);

                    fStream.Close();

                    oweb.AllowUnsafeUpdates = true;

                    SPFile thumbFile = Thumbfolder.RootFolder.Files.Add(Path.GetFileName(thumbpath), contents, true);

                    thumbnailURL = oweb.Url + "/" + Thumbfolder.RootFolder.Url + "/" + thumbFile.Name;

                    //Update field 'Thumbnail' (Preview Image URL) in AssetLibrary:

                    SPFieldUrlValue thumurl = new SPFieldUrlValue();

                    thumurl.Url = thumbnailURL;

                    thumurl.Description = "";

                    oitem["Preview Image URL"] = thumurl;

                    this.EventFiringEnabled = false;

                    oitem.SystemUpdate(false);

                    this.EventFiringEnabled = true;

                    oweb.AllowUnsafeUpdates = false;

                    //Delete file Thumbnail in temp local folder:

                    try

                    {

                        File.Delete(thumbpath);

                    }

                    catch { }

                }

 

                // Delete file video in temp local folder:

                try

                {

                    File.Delete(filevideopath);

                }

                catch { }

            }

        }

    }

}

 

private void RunProcess(string ffExe, string Parameters, int timeout)

{

    //create a process info

    ProcessStartInfo oInfo = new ProcessStartInfo(ffExe, Parameters);

    oInfo.UseShellExecute = false;

    oInfo.CreateNoWindow = true;

    //try the process

    try

    {

        //run the process

        Process proc = System.Diagnostics.Process.Start(oInfo);

        proc.WaitForExit(timeout); //wait until timeout

        if (proc.HasExited == false)

            proc.Kill();

    }

    catch (Exception)

    {

    }

}

 

Share this post: | | | |
Bagaimana memasang Event Receiver hanya ke List tertentu

Bagaimana memasang Event Receiver hanya ke List tertentu ?

Dari bawaan feature-nya, konfigurasi pemasangan event receiver hanya menyediakan target List Template, sehingga ketika di-deploy otomatis event receiver akan terpasang di semua list dengan list template yang sama yang sudah ditentukan sebelumnya.

Namun bagaimana jika kita hanya ingin memasang event receiver ke list tertentu saja. Tidak ada cara lain kecuali meng-override pemasangan yang dilakukan feature dengan kode kustom yang kita buat.

Berikut langkah-langkahnya :

1. Mulailah project Anda dengan template kosong, sehingga anda mendapati feature yang masih kosong. Atau jika ada menginginkan di project yang sudah ada, maka hapus saja semua yang ada di 'Items in the Feature'  

2. Kemudian pilih feature, klik kanan dan "add event receiver".

3. Dan sekarang kita mendapati kode event FeatureActivated and event FeatureDeactivating yang akan kita timpa. Di FeatureActived kita taruh kode untuk memasang event receiver kita ke list yang kita tentukan, dan di FeatureDeactivating kita taruh kode untuk mencopot event receiver dari list yang kita tentukan.

4. Berikut contoh kode lengkapnya:

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

    string asmname = this.GetType().Assembly.GetName().Name;

    string asmfullname = this.GetType().Assembly.FullName;

    SPWeb site = (SPWeb)properties.Feature.Parent;

    SPList olist = site.Lists.TryGetList("ListSaya");

    SPEventReceiverDefinition itemAddedEventReceiver = olist.EventReceivers.Add();

    itemAddedEventReceiver.Name = asmname;

    itemAddedEventReceiver.Type = SPEventReceiverType.ItemUpdated;

    itemAddedEventReceiver.Assembly = asmfullname;

    itemAddedEventReceiver.Class = typeof(EventReceiver1.EventReceiver1).FullName;

    itemAddedEventReceiver.Update();

    olist.Update();

}

 


public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

    String AssemblyName = this.GetType().Assembly.FullName;

    SPWeb site = (SPWeb)properties.Feature.Parent;

    SPList olist = site.Lists.TryGetList("ListSaya");

    SPEventReceiverDefinitionCollection erdc = olist.EventReceivers;

    List<SPEventReceiverDefinition> eventsToDelete = new List<SPEventReceiverDefinition>();

    foreach (SPEventReceiverDefinition erd in erdc)

    {

        if (erd != null)

        {

            if (erd.Assembly.Equals(AssemblyName))

                eventsToDelete.Add(erd);

        }

    }

    foreach (SPEventReceiverDefinition er in eventsToDelete)

    {

        er.Delete();

    }

    olist.Update();

}

Share this post: | | | |
Poping up standard Sharepoint Dialog to show PDF file when clicking the item link

Let say , you want: when clicking item link di display form, the lightbox style dialog is poped up to display some details. Then you can utilize Sharepoint standard Modal Dialog (SP.UI.ModalDialog). Here is my best practice for that using Sharepoint Designer 2010 to edit item link and CEWP to put javascript required:

1. For the sake of simplicity to edit and stability (in some cases I'll missed them when using Sharepoint Designer), I put the javascript required in CEWP. the script is :

<script type="text/javascript">
function openDialog(purl,ptitle) {
  var options = {
    url: purl,
    width: 600,
    height: 400,
    title: ptitle,
  };
  SP.UI.ModalDialog.showModalDialog(options);
}
</script>

You can learn that script from many resources in internet. I don't put dialogReturnValueCallback parameter because I don't need evaluate return value when dialog is closed.

 2.  Open page in Sharepoint Designer, look for the tag link ( <a> ) , do "edit Tag". Clean up all attribute except "href:" off course (It's important because I get "Invalid Page URL" message when I didn't do it). Change the href attribute value as you need to. Below is my case :

<a href=" javascript : openDialog('http://mysite.co.id{$thisNode/@FileRef.urlencodeasurl}','Viewer')">

cause I need to show the pdf file in popup windows (off course you need pdf viewer plugin activated in browser).


Share this post: | | | |
Update ListItem yang tidak jalan di Event Added

Update ListItem yang tidak jalan di Event Added :

Secara default Event ItemAdded adalah asynchronous event, jadi terkadang ada masalah proses Update ListItem tidak jalan di event ItemAdded dikarenakan disitu ada proses lain juga yang butuh waktu lama sehingga sampai didahului oleh munculnya form Edit Form. Untuk itu supaya form Edit tidak muncul sebelum proses di event ItemAdded selesai, maka event ItemAdded harus dirubah dari asinkron ke sinkron, seperti berikut :

itemAddedEventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous;


Reference:

http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/956f2529-07f7-4c38-9a0a-fded82ad3bce
http://wineya.blogspot.com/2010/03/binding-asynchronous-event-handlers-as.html

Share this post: | | | |
Sample PowerShell Script untuk Move File, Create Folder, dan Get-Date

Deskripsi:

Script dibawah mencari file PDF yang karakter 3&4nya adalah "ID" di 2 folder (Folder_A dan Folder_B). Bila ketemu membentuk subfolder  tanggal sekarang+1 berformat "yyMMdd", lalu memindahkan file PDF tersebut ke subfolder yg terbentuk

$arrfolder="D:\Root\Folder_A","D:\Root\Folder_B"
foreach ($folder in $arrfolder)
{
    $files = [System.Io.Directory]::GetFiles($folder,"*.pdf")
    foreach ( $fi in $files)
    {
        $fi1 = New-Object system.IO.FileInfo $fi
        if ($fi1.Name.Substring(2,2) -eq "ID" )    {
            $subfolder = get-date -format yyMMdd ((get-date).adddays(1))
            $path = $folder+"\"+$subfolder
            if ([system.io.Directory]::Exists($path) -eq $False ) { 
            try {
                $di  = [System.Io.Directory]::CreateDirectory($path)
                }
            catch {
                "create folder failed"
                }
            }
            Move-Item $fi $path -force
        }
        else {
            Remove-Item $fi
        }
    }
}

Share this post: | | | |
Posted: Nov 02 2010, 09:49 PM by pdanan | with 1 comment(s)
Filed under: