Tuesday, April 3, 2012

Creating BCS Model

Steps i am following to create my first BDC model in VS2010

1. Open VS and create an empty sharepoint project.
2. Create a folder "BDC", right click on it to add new item.
3. Select Bussiness data connectivity model and name it, "BDCModel" in my case.
Followed step mentioned in following posts.

http://sharepoint.microsoft.com/blog/Pages/BlogPost.aspx?PageType=4&ListId={72C1C85B-1D2D-4A4A-90DE-CA74A7808184}&pID=444
http://sharepoint.microsoft.com/blog/Pages/BlogPost.aspx?PageType=4&ListId={72C1C85B-1D2D-4A4A-90DE-CA74A7808184}&pID=433

One thing to me noted is Type of Return parameterz Type descriptor should be like this.
Name-of-project.ClassName,ModelName

- Set ReadOnly Property to Nothing for Create and Update Methods

- Add Settings.setting file
- Add ConnectionString in file

Add Following code in Service Class
-- ReadItem
 public static TestClass ReadItem(int testID)
        {
            using (BCSLearningDataContext context = new BCSLearningDataContext(Settings.Default.ConnectionString))
            {
                 TestClass  testClass= context. TestClass  .Where(e => e.TestID ==  testID ).FirstOrDefault();
                return  testClass ;
            }
        }
-- ReadList
        public static IEnumerable< TestClass  > ReadList()
        {
            using (BCSLearningDataContext context = new BCSLearningDataContext(Settings.Default.ConnectionString))
            {
                List< TestClass  > dbTestClass= new List< TestClass  >();
                 dbTestClass = context. TestClass  .ToList< TestClass  >();
                return  dbTestClass ;
            }
        }
-- Create
public static  TestClass   Create( TestClass   newTestClass)
        {
            using (BCSLearningDataContext context = new BCSLearningDataContext(Settings.Default.ConnectionString))
            {
                context. TestClass.InsertOnSubmit( newTestClass );
                try
                {
                    context.SubmitChanges();
                    return  newTestClass ;
                }
                catch (System.Data.Linq.ChangeConflictException ex)
                {
                    string error = ex.Message;
                    throw ex;
                }
         
            }
        }
-- Delete
       public static void Delete(int testID)
        {
            using (BCSLearningDataContext context = new BCSLearningDataContext(Settings.Default.ConnectionString))
            {
                 TestClass testClass= context.TestClass .Where(e => e.TestID ==  testID ).FirstOrDefault();
                context. TestClass  .DeleteOnSubmit( testClass );
                try
                {
                    context.SubmitChanges();
                }
                catch (System.Data.Linq.ChangeConflictException ex)
                {
                    string error = ex.Message;
                    throw ex;
                }
           
            }


        }
--Update

 public static void Update(TestClass testClass)
        {
            using (BCSLearningDataContext context = new BCSLearningDataContext(Settings.Default.ConnectionString))
            {
                 TestClass  dbTestClass= context. TestClass.First(thisTest => thisTest.TestID.Equals( testClass.TestID ));
                 dbTestClass.Col1=  testClass.Col1 ;
                 dbTestClass.Col2=  dbTestClass.Col2;
                ...
                try
                {
                    context.SubmitChanges();
                }
                catch (System.Data.Linq.ChangeConflictException ex)
                {
                    string error = ex.Message;
                    throw ex;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }


-- Creating a project to add custom web parts and display data of external list i have created yet.

Step 1. Added Empty sharepoint project.
Step 2. Added Feature.
Step 3.Added following MApped folders.
 - Images
 - Layouts
 - CONTROLTEMPLATES

Step 4. Added new Folder WebParts.
Step 5 Added Visual web part
Added reference to BDCModel project.

Added Access list have columns of external list to bind data to gridview.
BCSLists > Lists > GenericList

-- A class having common functions used by all lists classed and generic functions

public abstract GenericList
{
        protected string listName;
        protected SPList list = null;
        protected bool fromRootWeb = false;

 public GenericList(string listName)
        {
            this.listName = listName;
        }
        public GenericList(string listName, bool fromRootweb)
        {
            this.listName = listName;
            this.fromRootWeb = fromRootweb;
        }


        public string ListName
        {
            get { return listName; }
        }


        public SPList List
        {
            get
            {
                if (list == null)
                {
                    try
                    {
                        list = fromRootWeb ? SPContext.Current.Site.RootWeb.Lists[this.ListName] : SPContext.Current.Web.Lists[this.ListName];
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Unable to access list:" + this.listName);
                    }
                }
                return list;
            }
          }
}

 > BCSLists > Lists > ListTestClass.cs
--1. Added reference to Microsoft.Sharepoint

-- Added a chil class "Columns" , having
-- Added all List Columns in this class.
(e.g) public const string BDCIdentity = "BDC Identity";

-- Added another class "TableColumns" Mapping DB table columns.
(e.g) public const string BDCIdentity = "BdcIdentity";

-- Added a constant mapped to List exact name
(e.g) public const string ListNameTestList = "TestList";

--

Creating a SharePoint 2010 Project



http://www.jones.bz/index.php/2010/05/15/developing-a-bdc-model-on-visual-studio-2010-for-sharepoint-foundation-2010-the-bdc-model-and-external-references/
http://www.jones.bz/index.php/2010/05/08/developing-a-bdc-model-on-visual-studio-2010-for-sharepoint-foundation-2010-install-create-and-deploy/

http://sharepoint.microsoft.com/blog/Pages/BlogPost.aspx?PageType=4&ListId={72C1C85B-1D2D-4A4A-90DE-CA74A7808184}&pID=433

http://fabiangwilliams.wordpress.com/2009/12/03/creating-a-sharepoint-2010-external-content-type-with-crud-methods-using-linq-and-a-sql-lob-system/

Monday, April 2, 2012

AJAX call to post/ get data

Post data to handler


function PostData() {

             if ($("#txtComment").val() != "") {
                 $("#spMessage").text("Please wait...");
                 var postData = {comments: $("#txtComment").val(),photoId: pid };
               
                $.ajax({

                    type: 'POST',
                  //  dataType: 'json',
                    url: "Handler/handerlername.ashx",
                    // contentType: 'application/json',
                    cache: false,
                    data: postData,
                    success: OnComplete,
                    error: OnFail
                });
                return false;
            }
        }


 function OnComplete() {
          // Load comment in a div
            $("#comments").load("Handler/HanderName.ashx?pid=" + pid+"&random=" + Math.random() * 99999);
     
        }

        function OnFail() {

            $("#spMessage").text("Error in Processing");
        }


// Handler Code to fetch Data

 public void ProcessRequest(HttpContext context)
        {
            
            int photoId = 0;
            int totalRows = 0;
            StringBuilder sb= new StringBuilder();
            photoId = clsCommon.ParseInt(context.Request["pid"]);
           

            DataTable table = GetDataTable()// Data from database
            if (table != null && table.Rows.Count>0)
            {

                foreach (DataRow dr in table.Rows)
                {
                  // Append html
                }

            }
            context.Response.Write(sb.ToString());
            
        }

// Handler Code to post data
  public void ProcessRequest(HttpContext context)
        {
          
           string Comments = string.Empty;
           int PhotoId = 0;
           int Memberid = 0;
            if (context.Request.RequestType == "POST")
            {
                // Logic to insert data in database
                if (result)
                {
                    context.Response.Write("Success!");
                }
                else
                {
                    context.Response.Write("Error in Processsing!");
                }


                
            }
            else
            {
                context.Response.Write("Data was not sent properly");
            }
        }

SQL pagination help

This code is just for my reference.

declare @t table                    
        (                    
          idx int identity,                    
          intColumnID int, primary key clustered( idx)        
        )


declare @rowcount int,                    
        @total INT,                    
        @return_value int  
       
   select @rowcount = (@intPageId + 5) * @intpageSize
   select @intPageId = @intPageId - 1
 
 if @intPageId < 0
select @intPageId = 1;

insert into @t

select   ColumnId from [dbo].tablename where
-- Condition  add all conditions here to make sure that count will b correct

 select  @total = @@rowcount
        set rowcount @intPageSize
    -- Insert statements for procedure here

SELECT * from @t t
join tablename on tablename.columnId=t.intColumnID
WHERE   t.idx >= @intPageId * @intPageSize + 1

order by t.idx    asc
return @total

Date Comparison javascript

 function ValidateDate(sender, args) {
        args.IsValid = false;

        try {

            if (document.getElementById("<%=txtDate.ClientID %>").value != "") {
                var todaydateDate = new Date();
                var bgnDate = document.getElementById("<%=txtDate.ClientID %>").value;
                var dt1 = new Date(bgnDate);
                var dt2 = new Date();
                dt2.setDate(dt2.getDate() + 14);
             

                if (dt1 > todaydateDate && dt1 > dt2) {
                    args.IsValid = true;
                    return true;
                }
                else {
                    return false;
                }

            }
            else {
                args.IsValid = true;
                return true;
            }


        }
        catch (err) {

            alert(err.Description);
        }

    }

Regular Expression to validate Date

ValidationExpression="(\d{1,2})[- /.](\d{1,2})[- /.](\d{4})"
                   

Check Max length of text area javascript

// Check Max length of text area
//  onkeypress="javascript:return checkLength(this,event);"
function checkLength(textbox, e,maxlength) {


    if (!checkSpecialKeys(e)) {
        if (textbox.value.length > maxlength) {
            if (window.event)
                e.returnValue = false;
            else
                e.preventDefault();
        }
    }

}

function checkSpecialKeys(e) {
    if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
        return false;
    else
        return true;
}

Validate Numeric input javascript

// Validate Numeric Input

// onKeyPress="javascript:return MoveCursorNext(event,this.id);"
function MoveCursorNext(evt, num) {
    var charCode = (evt.which) ? evt.which : event.keyCode


    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
}