How to UseIt's Not Open Source but It's Free


Download

Download this version from Here

Or Download From Nuget:
PM > Install-Package MBS.SharePoint.Mapper loading

SPMapper

SPMapper

How to use these classes ?

Step 1: There is a BaseList class .You have to make a new class as a child of this class. (derived from BaseList) like MyListEntity in the diagram above.
This class contains all Properties of you list entity (that you need to work as your SharePoint List fields).

Attention: Please pay attention to field type that you select to work with. For example, [Due Date] field type is DateTime

Attention: Please pay attention to field name. this component works with InternalName of fields So, you must set the name of properties accordning to that. If your internal name is encoded like TRV_x0020_Main_x0020_Calendar , you can use InternalNameAttribute to force this new name. For example,for field with name "Due Date" you can make a property with name DueDate (as one non-space word) and use attribute of [InternalName("Due_x0020_Date")]

Attention: BaseList class contains Item Template fields (shown in diagram above) and you do not need to add them again (like: ID, Title & ...)

Attention: Please pay attention to fields that is not updatable or insertable. Those can be flagged by IgnoreActionAttribute

Attention: You have to override the GetListTitle() method to find the list by title of list.
also, you can override the GetListId() method to find by ListID (if find by title failed)

Example

                /*
                using Seifollahi.SPMapper
                */

                class MyListEntity: BaseList
                {
                    public override string GetListTitle()
                    {
                        return "My List Title"; // your list title, to find please go to ListSetting 
                    }

                    /*
                    public override Guid GetListId()
                    {
                        return Guid.Empty; // optional setting
                    }
                    */


                    [InternalName("Due_x0020_Date")] 
                    public DateTime DueDate { get; set;}

                    public string Body { get; set; }
                    public string Importance { get; set; }
                    public int Assessment { get; set; }

                    [InternalName("_dlc_BarcodeValue")]
                    public string BarcodeValue { get; set; }

                    [IgnoreAction(Enums.Actions.Update)]
                    public string DoNotUpdateField{ get; set;}

                }


                

Step 2: There is an ISPWeb interface. Again, you have to make a new class (inherited from this interface). This interface represnet a GetWeb() method the returns a SPWeb object. You should find the web (that you need to work with) inside your new class.

Example

                 /*
                 using Seifollahi.SPMapper
                 using Seifollahi.SPMapper.Interface

                */

                 // a simple sample
                 class MyWeb : ISPWeb
                 {
                     SPWeb tmp=null;
                     public MyWeb(SPWeb web)
                     {
                         tmp = web;
                     }
                     public SPWeb GetWeb()
                     {
                        /*
                        You can use SPSite object to OpenSite or SPWeb object 
                        to make a new object of your web, but you must 
                        manage the object life cycle and disposing issues.
                        */

                         return tmp;
                     }
                 }



                

Step 3: Now, you can use SPMapper Generic class to apply CRUD. You sould make an instance of SPMapper class as below:

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    // as shown above
                    MyWeb web = new MyWeb(SPContext.Current.Web);


                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);
                    // now,it's ready to work
                 }


                

Select

Select Item

After Step 3 done (as mentioned above), you can use CRUD method:

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    // get list item with ID = 26
                    MyListEntity item26 = myList.Select(26);

                 }

                

Select Items

Also, you can use SPQuery object to make your own query on a list and use that query to fetch data:

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    SPQuery q = new SPQuery();
                    q.Query = @"< Where> < Eq>< FieldRef Name='ExpenseType'   />< Value Type='Text' >Fuel< /Value>
                               < /Eq> < /Where>< OrderBy>< FieldRef Name='ExpenseDate' Ascending='True' />< /OrderBy>";
                    q.RowLimit = 50;

                    List< MyListEntity> items = myList.Select(q);

                    gridview1.DataSource = items;
                    gridview1.DataBind();
                 }

                

Add

Add Item

In 3 easy steps: make a new object of your entity list, set the values, add it to list ... Finished (You Need Enough Permission)

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    var newItem = new MyListEntity{Title = "New Title" 
                                    ,Body ="My Test Body content from SPMapper",Assessment = 10};
                    myList.Add(newItem);
                    
                    /*
                    if you want the ID of new added item , just get as below 
                    
                    int id = newItem.ID;
                    
                    */
                 }

                

Update

Update Item

Update any fields you want. You need just the ID of ListItem.(You Need Enough Permission)

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    // make an object with ID property (here ID = 400)
                    // and set other fields 
                    var item = new MyListEntity{ID = 400,Title = "Updated item Title" 
                                    ,Body ="My New Body content from SPMapper after update",Assessment = 777 };
                    
                    myList.Update(item, z=> new object[] {z.Title , z.Body, Assessment });
                    
                 }

                

Delete

Delete Item

Set the Item ID then Remove it. (You Need Enough Permission)

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    // set the ID of Item to delete
                    int idToDelete = 105;

                    myList.Delete(idToDelete);
                    
                 }

                

Advanced

Advanced Setting

There are two types of Save Action in SharePoint (For Updating the ListItem).
One save action will update the Editor fields and date of edition and will make a new version of that item, and another will not make a new version and save as Anonymouse without updating date of edition.

To access this type of setting, you can change the value of SaveAsNewVersion in constructor of SPMapper class. Default of this property is true.

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);

                    bool _saveAsNewVersion = false; // default is true.

                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web,_saveAsNewVersion);

                   // call your update method
                    
                 }

                

BaseList (Default) , Override your BaseList

Default IgnoreAction attribute of BaseList Properties are:

Column Attribute
ID Enums.Actions.UpdateAndInsert
Title [Not Set]
Created Enums.Actions.UpdateAndInsert
Author [Not Set]
Editor [Not Set]
Modified Enums.Actions.UpdateAndInsert

You can override your attribute by overriding the properties and your own IgnoreAction attribute

Example

                 /*
                using Seifollahi.SPMapper
                */

                class MyListEntity: BaseList
                {
                    public override string GetListTitle()
                    {
                        return "My List Title"; // your list title, to find please go to ListSetting 
                    }

                    [IgnoreAction(Enums.Actions.None)] // make this field updatable via coding
                    public override DateTime Modified
                    {
                        get;
                        set;
                    }

                     [IgnoreAction(Enums.Actions.Update)] // do not update Title field 
                     public override string Title
                     {
                         get;
                         set;
                     }


                }

                   

Safe Control

To use this component in your SharePoint solution, you should add this as a safe control. See the below:

                // add it to SharePoint Package

                < SafeControl Assembly="Seifollahi.SPMapper, Version=1.0.0.1, Culture=neutral, 
                PublicKeyToken=795d33ebcf5a747e" Namespace="Seifollahi.SPMapper" 
                TypeName="*" Safe="True" SafeAgainstScript="False" />

                //add it to SharePoint Package

            

Helper Classes & Extensions

There are some helper classes and methods to get more functionality. Some of them are:

                // Work With DateTime

                // Jalali Date Convertor
                string shamsi = DateTime.Now.ToShamsi();

                
                // Jalali Date Convertor with DateItem
                DateItem ditem = new DateItem();

                string shamsi = DateTime.Now.ToShamsi(out ditem);
                int day = ditem.Day;
                int month = ditem.Month;
                int year = ditem.Year;





                // Work With SharpColon

                // split string
                string userinfo = "1073741823;#System Account";
                ColonSharp user = ColonSharp.Parse(userinfo); 
                // if parsing failed, will retuen an instance with no data

                string id = user.ID; // 1073741823
                string userName = user.Value; // System Account

                // merge string
                ColonSharp user = new  ColonSharp("1073741823","System Account");
                string merged = user.ToString();

                // Or
                // Use DateExtensions
                using Seifollahi.SPMapper.Static;

                string merged = DateExtensions.GenerateSharpColon("1073741823","System Account");





                // Work With SPHelper
                using Seifollahi.SPMapper.Static;

                try
                {
                 // do something with exception
                }
                catch(Exception ex)
                {
                    ex.SPTraceLogError();
                    // this method log your exception in 14 (or 15) folder of HIVE in logs folder.
                    // default category name is "SEIFOLLAHI.SPMAPPER"
                    // you can change it : 
                    // SPHelper.ExceptionCategory  = "YOUR CATEGORY NAME"; // to find better in the logs
                }


                // Work With Choice Fields
                using Seifollahi.SPMapper.Static;

                SPList mylist = GetListMethod("Tasks"); // assumption: there is a method to find Task List
                
                List< string> items = mylist.GetChoiceFieldValues("Priority");

                // you can see all items of ChoiceField
                


              

Attachment

Get Attachment

You can get all attachments of an item easily. This method returns an instance of Attachment class.

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                    MyWeb web = new MyWeb(SPContext.Current.Web);

                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);

                    // for item with ID = 8
                    Attachment attachments = myList.SelectAttachment(8);
                    
                    if(attachments.HasAttachment)
                    {
                        // do somethings like 
                        // string url = attachments.UrlPrefix + attachments.Files[0];
                    }

                 }

                

Add Attachment

You can use AddAttachment method to add a new attachment file to a list item.

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 protected void uploadFile(object sender, EventArgs e)
                 {
                   
                    // start uploading a file
                    byte[] _byteArray;
                    string fileName = upldFile.PostedFile.FileName;

                    using (System.IO.Stream strm = upldFile.PostedFile.InputStream)
                    {
                        _byteArray = new byte[strm.Length];
                        strm.Read(_byteArray, 0, (int)strm.Length);
                    }

                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);


                    // set AllowUnsafeUpdates = true to allow update (you should do this if necessary )
                    web.GetWeb().AllowUnsafeUpdates = true;

                    // upload a file for item with ID = 10
                    myList.AddAttachment(10, fileName,_byteArray);


                 }

                

Delete Attachment

You can also remove the attachment file.

Example

               
                /*
                using Seifollahi.SPMapper
                */

                 void SampleMethod()
                 {
                   
                    MyWeb web = new MyWeb(SPContext.Current.Web);
                    Mapper< MyListEntity> myList = new Mapper< MyListEntity>(web);
                    
                    // Delete attachment of item with ID = 10 and fileName is "myImageName.png"
                    // Be sure the file name is correct
                    myList.DeleteAttachment(10, "myImageName.png");

                 }

                

Pagination

Pagination

How to use these classes ?

In life cycle of a web Page, in a normal form, you must initialize the control to bind with the data source, and on NextPage event and PreviousPage event, you need to rebind your control with data, but with different data.
Also, you need to store pagination meta data in a storage like ViewState or Session.
Assumed that you have a GridView and 2 LinkButton (lnk_next,lnk_prev) on the page (for navigation to next and previous page) and a Literal to show current page (lit1).

Attention: You should set all the event to handle pagination.

Attention: This version supports just one column sorting.

Step 1: Make a method with return type of QueryPaging


             // using Seifollahi.SPMapper.Pagination
	     
             QueryPaging< MyListEntity> Paging()
             {
                 var web = new Mapper.Web(SPContext.Current.Web);
          
                 // pagination works on list of T (T here is MyListEntity)
                 QueryPaging< MyListEntity> ps = new QueryPaging< MyListEntity>(web);
          
                 // default is ID
                 ps.SortColumn = "Title";
                 
                 // default is 10
                 ps.PageSize = 2;

                 /*
                 
                 if you want to use your SPQuery object to paging, go as below:

                 SPQuery qq = new SPQuery();
                 qq.Query = "< Where>< Leq>< FieldRef Name=\"ID\" />< Value Type=\"Counter\">10< /Value>< /Leq>< /Where>";
                 qq.RowLimit = 4;
                 ps.Query = qq; // this assignment will apply as an override for [PageSize]
                                // but you should also set the value of [SortColumn]
                 

                 another exmaple with sort column:

                 SPQuery qq = new SPQuery();
                 qq.Query = "< Where>< Leq>< FieldRef Name=\"ID\" />< Value Type=\"Counter\">10< /Value>< /Leq>< /Where>"+
                             < OrderBy>< FieldRef Name='Importance'/>< /OrderBy>;
                 
                 qq.RowLimit = 4;
                 ps.SortColumn = "Importance";
                 ps.Query = qq;

                 */
          
                 ps.onPageChanged += new QueryPaging< MyListEntity>.PageChanged(ps_onPageChanged);
                 ps.onDataBind += new QueryPaging< MyListEntity>.DataBind(ps_onDataBind);
                 ps.onPagingRetrieval += new QueryPaging< MyListEntity>.PagingRetrieval(ps_onPagingRetrieval);
                 ps.onSaveInformation += new QueryPaging< MyListEntity>.SaveInformation(ps_onSaveInformation);
          
                 return ps;
             }
              

Step 2: set all events

             // store information of pagination (represents a query string with some parameters) in a ViewState
              void ps_onSaveInformation(PagingStorageEventArgs e)
              {
                  ViewState[e.PagingInformationType.ToString()] = e.Information;
              }
             
                // load stored information of pagination from ViewState
                 string ps_onPagingRetrieval(Enums.PagingInfo p)
                 {
                     return Convert.ToString(ViewState[p.ToString()]);
                 }
             
                 // Bind data 
                  void ps_onDataBind(System.Collections.Generic.List< MyListEntity> result)
                  {
                      grd1.DataSource = result;
                      grd1.DataBind();
                  }
             
                 // handle pagination Links and lables 
                  void ps_onPageChanged(PageRecognitionEventArgs e)
                  {
                      lnk_next.Visible = e.HasNext;
                      lnk_prev.Visible = e.HasPrevious;
                      lit1.Text = e.PagingLabel;
                  }
             

Step 3: call Method

            
              protected void Page_Load(object sender, EventArgs e)
              {

                  if (!IsPostBack)
                  {
                      // Paging method works like a Thread Safe Method
                      // because last state of pagination stored in ViewState
                      Paging().Init();
                  }
              }


              protected void nextClick(object sender, EventArgs e)
              {
                  Paging().NextPage();
              }

              protected void prevClick(object sender, EventArgs e)
              {
                  Paging().PreviousPage();
              }

            

Changes

Changes in this version

It's the first version and there is no changes.