Wednesday 19 June 2013

Filter list views by user groups

Though SharePoint Designer is a powerful tool, but even then there is a limitation to filter list views by user group. Only filter that can be applied is by using keyword [Me]. So if current user is the member of any group, then the [Me] keyword filter won't work.

The alternative idea is to use the Membership comparator, which is used by the "By My Groups" view. The Membership comparator seems to work just like the other comparators ("is equal to", "is greater than", "is less than", etc), but is not available in the "Filter" section of view.

Try following these steps:

  • Create a new view, and open the corresponding Aspx in Sharepoint Designer
  • In the source code, locate the ListViewXml tag
  • Inside this tag, locate the Where clause (begins with "<Where" and ends with "/Where>")
  • Replace the contents of this tag with the following:
<Where><Or><Membership Type="CurrentUserGroups"><FieldRef Name="AssignedTo"/></Membership><Eq><FieldRef Name="AssignedTo"/><Value Type="Integer"><UserID Type="Integer"/></Value></Eq></Or></Where>
Save the page, and you're ready to go.

How Do I Restrict Views of a Custom List by Group in Sharepoint 2007?

SPServices - http://spservices.codeplex.com/
In sharepoint, create a non-public library called "Jquery libraries" and upload your jquery and SPServices to it.
In sharepoint designer, create a copy of AllItems.aspx.
In sharepoint designer, edit the file AllItems.aspx. Clear all the code and insert this javascript code.
        <script language="javascript" type="text/javascript" src="PATH-TO-YOUR-JQUERY-FILE"></script>
<script language="javascript" type="text/javascript" src="PATH-TO-YOUR-SPSERVICES-FILE"></script>

<script type="text/javascript">
$(document).ready(function() {
    //Get current username
    userName = $().SPServices.SPGetCurrentUser({
        fieldName: "Name",
        debug: false
    });

    //get user's group
    $().SPServices({
        operation: "GetGroupCollectionFromUser",
        userLoginName: userName,
        async: false,
        completefunc: function(xData, status){

            $(xData.responseXML).find("Group").each(function(){
                if(status == "success"){
                    var nomeGrupo = $(this).attr('Name');
                    //if user is in group 1 redirect to page 1. If user is in group 2 redirect to page 2 etc...
                    if(nomeGrupo=="Grupo sergio"){
                             window.location.replace("PATH-TO-PAGE-1/SomeItems.aspx");
                    }else{
                        window.location.replace("/PATH-TO-PAGE-2/ViewAll.aspx");
                    }

                }else{
                    alert("Falha na comunicação com o Sharepoint");
                }
            });
        }
    });
});
</script>
This code will redirect the user to other pages that will contain customised web-parts-view.
In sharepoint design, rename the AllItems.aspx to SomeItems.aspx (for example).
You can create multiples copys of this file and follow the next step to customise it.
Edit this file and delete the main webpart located at PlaceHolderMain.(Tip: u can click and delete if u are in split view(code an design) in sharepoint designer).
Then, you can insert a custom web part view for your list. In this custom view, you can filter data or not display some colums.

Download JQuery and SPServices libraries and place them in a read only document library or in your 14 Hive, whichever suits you. Then edit the NewForm.aspx of the list (with SP Designer) and add in references to the two files.
Add a script tag with the following:
$(document).ready(function() {
    Admin_Group = "My Group Name";
    if(IsGroupMember(Admin_Group))
    {
        $('input[title="Assigned To"]').parent().parent().css("display","none");
    }
});


function IsGroupMember(GroupName)
{
    var isGroupMember = false;
    $().SPServices({
            operation: "GetGroupCollectionFromUser",
            userLoginName: $().SPServices.SPGetCurrentUser(),
            async: false,
            completefunc: function(xData, Status) {
              if($(xData.responseXML).find("Group[Name='" + GroupName + "']").length == 1)                
              {
                  isGroupMember = true;
              }
            }
    });
    return isGroupMember;
}
You might need to check the input selector is correctly accessing the assignedto or what ever field you need to hide but I've used this approach successful in many situations. Make sure the field you hide isn't a required field. Also remember to hide this in the EditForm.aspx too if thats what you need.

Hi I managed to hide a field programmatically see below. The Approve field is now hidden in the edit screen of the list
SPField Appprove = bdcList.Fields.GetField("Approved");
                        Appprove.ShowInEditForm = false;
                        Appprove.ShowInDisplayForm = true;
                        Appprove.ShowInNewForm = false;
                        Appprove.Update();

How to restrict public access to SharePoint lists using views with filters

 13
How to restrict public access to SharePoint lists using views with filters
In SharePoint you can either create a personal or a public view on document libraries, lists, and etc. You may come across situations where you need only a few individuals to see a particular view, such as one where all columns are not shown. Currently we are not able to control access to views with security settings. Microsoft may address this in the next release or a service pack. Until that time, here is a workaround that may work in many cases.
An example:
We have a custom list called Contracts containing software contract information in columns named:
  • customer
  • license type
  • product
  • contract date
  • contract currency
  • contract amount
This list already has contract data contained in it. We are required to allow everyone in the Sales Department to see this list. However, the contract amount should be visible only to few management executives. We will assume John Smith and Jane Smith are the two executives in the Sales Department who need to see the list views with the contract amount.
First : Set permissions on the list to allow everyone in the sales department READ permissions. This may require you to break security inheritance on the list.
Reminder: In SharePoint, if you give READ permission to a list or library, the person will also have READ permission to all public views. This means, by default, everyone is able to see all public views. READ permissions will not, however, allow the creation of public or private views.
Next: create a public view (or alter the "All Items" view) of the list that does not include the contract amount. Set it as the default view for the list.
Then: we alter our contract list.
On the list where you want to restrict access to views to one or more individuals:
  1. Create a column called "Restricted users" (This can actually be called anything. Just remember what you called it for later).
  2. Column Type = Person or Group
  3. Allow Multiple Selections =Yes
  4. Allow Selection of = People Only
  5. Choose From = All Users (This is the list of Users from your Active Directory)
  6. Show Field = Name (Choose this from the drop down)
  7. Open up the list in data sheet view.  [List Name]>>Actions>> Edit In Datasheet
  8. Scroll to the column called "Restricted Users" (or whatever you called it in Step 1 above).
  9. Under the "Restricted Users" column, in the first cell type John Smith;Jane Smith  ( These 2 names should be in Active Directory exactly as spelled, if not find the correct spelling before typing them in here).
  10. Copy this cell to the rest of the cells under the "Restricted Users" column and save.
Finally:  we create our restricted view 
  1. Create a view for this contract list, call it "Contract-Restricted"  or an appropriate name. This view should be created as a public view.
  2. Be sure to include the Contract Amount column to be displayed in this view.
  3. In the filter section where it says "show the items when"
    1. Choose "Restricted Users" from the dropdown list
    2. Condition =Is equal to
    3. In the text box type [Me]
How will it work?
The filter essentially looks at the current user logged in sharepoint, if it is John Smith or Jane Smith, the filter condition is met and it returns the result in the "Contract-Restricted" view otherwise the view will not return any result.
When non-sales department employees access the list, they will be denied because they have not been given READ permission. When regular sales people log in to the site and select the list, they will see the all items, but not the Contract Amount column, since we removed it from the default view. They will see both the of the public views we created, All Items and Contract-Restricted and be able to choose between them. But, when they choose the "Contract-Restricted" view they will not see any results because of the filter.
When John Smith or Jane Smith access the Contracts list they will see the default view like everyone else. However, when they select the "Contract-Restricted" view, they will see results that include the Contract Amount column.

Filter list view based on membership in SharePoint group

Filter list view based on membership in SharePoint group

This script filters a list view based on membership in SharePoint groups. The filtering has nothing to do with item level security, it is merely a method for filtering by comparing a users group membership against a text field containing a group name. This column “VisibleTo” must contain the actual group names from the “People and Groups” list in SharePoint.
This method gives you the ability to filter the list view based on multiple criteria. If the user is member of multiple groups, the list will display all items relevant to any of the groups. You may also specify that elements where the column “VisibleTo” is empty will be displayed for all visitors. The “VisibleTo” column can be a multiple choice checkbox type column.
As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG
The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.
The scripts “interaction.js” and “stringBuffer.js” is created by Erucy and published on CodePlex.
The script “AccessUserProfileInWSS.js” is found here.
Note:
  • If used in grouped views, you must have the groups initially expanded, otherwise the elements are not rendered and cannot be filtered.
  • Only one level of grouping is currently supported.
  • Boxed view are not supported.
  • The filter does not apply in a datasheet view.
Add a CEWP below the list view webpart, and add this code:
01<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
02<script type="text/javascript" src="../../Javascript/interaction.js"></script>
03<script type="text/javascript" src="../../Javascript/stringBuffer.js"></script>
04<script type="text/javascript" src="../../Javascript/AccessUserProfileInWSS.js"></script>
05<script type="text/javascript" src="../../Javascript/FilterListViewByGroupMembership.js"></script>
06<script type="text/javascript">
07  
08// Find the user login name
09var ui = getUserInfo(); 
10var userLoginName = ui['Name'];
11// Get the group collection for the current user
12var ug = getGroupCollectionObjFromUser(userLoginName);
13// Set the filter - if you want the results to include elements in a specific group by default, specify it in the array below
14filterVal = [];
15// Define the group - find the group ID in "People and Groups"
16var groupIdTeam1 = 145;
17var groupIdTeam2 = 146;
18// Build the filter - add more if's to complete your filter
19// Is the user member of the group with id 145?
20if(ug[groupIdTeam1]!=undefined){
21    filterVal.push(ug[groupIdTeam1]);
22}
23// Is the user member of the group with id 146?
24if(ug[groupIdTeam2]!=undefined){
25    filterVal.push(ug[groupIdTeam2]);
26}
27  
28// Call the function
29filterListViewByGroupMembership('VisibleTo',filterVal,true,true,true);
30</script>
The sourcecode for the file “FilterListViewByGroupMembership.js”:
001/* Filter list view by membership in SharePoint group - hide the column header and the filter column if specified
002 * -----------------------------
003 * Created by Alexander Bautz
004 * LastMod 15.02.2010
005 * -----------------------------
006 * Include reference to:
007    jquery - http://jquery.com
008    interaction.js - http://spjslib.codeplex.com/
009    stringBuffer.js - http://spjslib.codeplex.com/
010    AccessUserProfileInWSS.js
011    FilterListViewByGroupMembership.js
012 * -----------------------------
013   If used in grouped views, you must have the groups initially expanded, otherwise the elements are not rendered and cannot be filtered.
014   Note: only one group level is currently supported.
015*/
016  
017function filterListViewByGroupMembership(FieldInternalName,filterValueArr,includeEmpty,hideFilterCol,collapseGroupedViews){
018filterOK = true;
019    // Build object of all headings
020    if(typeof(filterColIndex)=='undefined'){
021        if(typeof(FieldInternalName)=='string'){
022            intName = FieldInternalName;
023            hideTD = hideFilterCol;
024            fvArr = filterValueArr;
025            inclEmpty = includeEmpty;
026        }
027        filterColIndex = '';
028        $(".ms-viewheadertr th").each(function(){
029            if($(this).find('table:first').attr('name')==intName){
030                filterColIndex = $(this).attr('cellIndex'); 
031                displayName = $(this).find('table:first').attr('displayname');
032                // If the parameter "hideFilterCol" is true, remove the column
033                if(hideTD){
034                    $(this).remove()
035                }
036            }
037        });
038          
039        if(filterColIndex==''){
040            filterOK = false;
041            var str = "<font color='red'>The column with FieldInternalName  "" + intName + "", must be in the view for the filter to work.</font>";
042            $("td.ms-toolbar[width='99%']").append("<div id='hoverDelayInfo' class='ms-listheaderlabel' style='text-align:center;margin-top:-15px'>" + str + "</div>");
043        }
044    }
045      
046    // Apply filter
047    if(filterOK){
048        // Build view header text
049        if(inclEmpty && fvArr.length==0){
050            fvArr.push('');
051            var fv = displayName + " = empty";
052        }else if(inclEmpty && fvArr.length>0){
053            fvArr.push('');
054            var fv =  displayName + " = " + fvArr.join(' or ') + " or empty";
055        }else if(!inclEmpty && fvArr.length==0){
056            var fv = "No filtervalues found - all items hidden";
057        }else if(!inclEmpty && fvArr.length>0){
058            var fv =  displayName + " = " + fvArr.join(' or ');
059        }       
060        // Insert view header text
061        if($("#filterInfo").length==0){
062            $("td.ms-toolbar[width='99%']")
063                .append("<div id='filterInfo' class='ms-listheaderlabel' style='text-align:center;margin-top:-15px'>" +
064                        "<span style='cursor:default'><img src='/_layouts/images/filter.gif'>&nbsp;" + fv + ".</span></div>");
065        }
066  
067        // Find all rows and apply filter
068        $("table.ms-listviewtable tbody:not([id^='aggr']) tr:has(td.ms-vb2) >td[cellIndex=" + filterColIndex + "]").each(function(){ 
069            var thisTd = $(this);
070            // Build array from all values in "Visible to" - column
071            var arrCurrTDtext = thisTd.text().split(';');
072            var keeper = false;
073            // Find all keepers
074            $.each(arrCurrTDtext,function(i,val){
075                var thisVal = $.trim(val);
076                if($.inArray(thisVal,fvArr)>-1){
077                    keeper = true;
078                }
079            }); 
080            // Remove the ones that do not match
081            if(!keeper){
082                thisTd.parents('tr:first').remove();                
083            }           
084            // If the parameter "hideFilterCol" is true, remove the column          
085            if(hideTD){
086                $(this).remove()
087            }
088        });
089          
090        // Test whether the view is grouped twice and give alert
091        if($("td.ms-gb2").length>0)alert("Sorry, but this script does not handle views grouped twice.");
092        // Loop trough every tbody to remove empty and to update item count
093        $("tbody[isloaded='true'][beenthere!='true']").each(function(){
094            $(this).attr('beenthere',true)
095            var gId = $(this).attr('id');
096            var gIdPart = gId.substring(4,gId.length-1);
097                // Number of elements remaining
098                var trLength = $(this).find("td.ms-vh-group").length;               
099                if(trLength==0){    
100                    // Remove the group heading and remaining elements for the group            
101                    $("#titl"+gIdPart).remove();
102                    $("#foot"+gIdPart+"_").remove();
103                    $(this).remove();
104                }else{
105                    // Write the new count to the group heading
106                    $("#titl"+gIdPart).find('td.ms-gb span:last').html("&lrm;(" + trLength + ")");
107                }
108        });
109          
110        // Collapse all groups - they must be expanded by default for the filter to apply
111        if(collapseGroupedViews){
112            $("td.ms-gb").each(function(){
113                $(this).find('a:first').click();
114            });
115        }
116          
117        // Fix highlighting of every other row
118        var classToFind = '';
119        if($("table.ms-listviewtable").find('tr.ms-alternating').length>0){
120            var classToFind = 'ms-alternating';
121        }else if($("table.ms-listviewtable").find('tr.ms-alternatingstrong').length>0){
122            var classToFind = 'ms-alternatingstrong';
123        }
124        if(classToFind!=''){
125            $("table.ms-listviewtable tr:has(td.ms-vb2)").each(function(i,row){
126                if(i%2==0){
127                    $(this).addClass(classToFind);
128                }else{
129                    $(this).removeClass(classToFind);
130                }
131                  
132            });
133        }
134          
135    }
136}
137  
138/*
139 * Function to get the groupCollectionfrocurrent user.
140 * Requires the scripts interaction.js and stringBuffer.js to be loaded
141*/
142function getGroupCollectionObjFromUser(userLoginName){
143    var result = {};
144    innerPost(wsBaseUrl + 'usergroup.asmx'
145        'http://schemas.microsoft.com/sharepoint/soap/directory/GetGroupCollectionFromUser',
146        '<GetGroupCollectionFromUser xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"><userLoginName>' + userLoginName + '</userLoginName></GetGroupCollectionFromUser>',
147        function(data){     
148            $('Group', data).each(function(idx, itemData){
149                result[$(itemData).attr('ID')] = $(itemData).attr('Name');
150            });
151        });
152    return result;
153}
154  
155// Attaches a call to the function to the "expand grouped elements function" for it to function in grouped listview's
156function ExpGroupRenderData(htmlToRender, groupName, isLoaded){
157    var tbody=document.getElementById("tbod"+groupName+"_");
158    var wrapDiv=document.createElement("DIV");
159    wrapDiv.innerHTML="<TABLE><TBODY id="tbod"+groupName+"_" isLoaded=""+isLoaded+"">"+htmlToRender+"</TBODY></TABLE>";
160    tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
161javascriptFilterView();
162}
Save as “FilterListViewByGroupMembership.js”, mind the file extension, and upload to the scriptlibrary as shown above.

Wednesday 12 June 2013

Integrating Sharepoint 2010 and SQL Reporting Services 2008 in 6 easy steps

Integrating Sharepoint 2010 and SQL Reporting Services 2008 in 6 easy steps

Step 1: Configuring SQL Reporting Services – Web Service URL
Simply go to Reporting Services Configuration Manager and choose Web Service URL and populate the following needed information. The fields are named properly so I guess there is no need for further explanation. What this does is that it configures the IIS for you depending on what Virtual Directory names you had declared.

Step 2: Configuring SQL Reporting Services – Create a Report Database

Same here, fields need no further explanation except for one which is Native Mode and SharePoint Integrated mode which I will explain below.
Choose create a database or if you already have one choose an existing one. For this example, we will create a new one:

Connect to the database where you want your Report Data to be stored:

Give it a Name and a Report Server Mode.
With SharePoint Integrated Mode the report RDLs are stored on SharePoint and not in the Report Database. For this instance, we will use the SharePoint Integrated Mode:

Specify the credentials that the report server will use to connect to the database.

Review your configuration.

Then wait while it's configured.

Step 3: Configuring SQL Reporting Services – Create a Report Manager URL

What this does is that it configures the IIS for you depending on what Virtual Directory names you had declared.

That’s it. At this point, your report server is configured for SharePoint Integration 2010.

Step 4: SharePoint Integration Configuration – Reporting Services Integration

Simply go to SharePoint 2010 Central Administration, then General Application Settings, then choose Reporting Services Integration.

Now populate the fields using the Web Service URL you had configured a while ago on Step 2 of this guide.

Once done, you will see the Activation State message.

Step 5: SharePoint Integration Configuration – Add a Report Server to the Integration

Now add the report server by putting the Server Name and the Server instance.

At this point it's all done, all you have to do now is try it out.

Step 6: Verify by Checking the Server and Uploading a Report

To verify if it's now integrated, go to Site Settings on your SharePoint Site, then Site Collection Features.


Check if the Report Server Integration Feature is Active, if not just click activate:

Now try to use the SQL Server Reporting Services Webpart:


Or you can also upload a report from a library.

That's it, so simple!

Thursday 6 June 2013

Fetching data from Excell to Sharepoint List

Dim s As String
Dim listName As String
Dim viewName As String
Dim strSoapAction As String
'Private oSoapClient As SoapClient30
Sub Button1_Click()
Call PublishList
End Sub
Option Explicit
Public Sub PublishList()
    ' WebService URL
    Dim serviceUrl As String
    serviceUrl = "http://einstein/sites/Vendors/_vti_bin/Lists.asmx"
    'serviceUrl = "http://zew-v-0ac2806f.vpc2-eu.aws.shell-cloud.com:84/sites/vendors/_vti_bin/Lists.asmx"
    'list guid for list name (SERP Create on Dev Seat http://zew-v-0ac2806f.vpc2-eu.aws.shell-cloud.com:84/sites/vendors)
    listName = "{1B3DFFF3-E3E4-435C-A1FA-C99181770F40}"
    'viewName = "{47B9A34B-38E7-44E2-B04D-08B38CAF1832}"
   
    s = "<Batch OnError='Continue' ListVersion='1' ViewName='" & viewName & "'>" & _
    "<Method ID='1' Cmd='New'>" & _
            "<Field Name='ID'>New</Field>" & _
            "<Field Name='Title'>Hello Indicator</Field>" & _
      "</Method>" & _
"</Batch>"
' Creating Soap Envelop
Dim soapEnv As String
soapEnv = "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">" & _
          "<soapenv:Body>" & _
            "<UpdateListItems xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">" & _
              "<listName>" & listName & "</listName>" & _
              "<updates>" & _
                    "<Batch OnError='Continue' ListVersion='1' ViewName='" & viewName & "'>" & _
                        "<Method ID='1' Cmd='New'>" & _
                            "<Field Name='ID'>New</Field>" & _
                            "<Field Name='Title'>Hello Ashok</Field>" & _
                        "</Method>" & _
                    "</Batch>" & _
              "</updates>" & _
            "</UpdateListItems>" & _
         "</soapenv:Body>" & _
        "</soapenv:Envelope>"
       
   strSoapAction = "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems"
 MsgBox soapEnv
  Call PostWebservice(serviceUrl, strSoapAction, soapEnv)
End Sub
Private Function PostWebservice(ByVal AsmxUrl As String, ByVal SoapActionUrl As String, ByVal XmlBody As String) As String
    Dim objDom As Object
    Dim objXmlHttp As Object
    Dim strRet As String
    Dim intPos1 As Integer
    Dim intPos2 As Integer
   
    On Error GoTo Err_PW
   
    MsgBox XmlBody
   
    ' Create objects to DOMDocument and XMLHTTP
    Set objDom = CreateObject("MSXML2.DOMDocument")
    Set objXmlHttp = CreateObject("MSXML2.XMLHTTP")
   
    ' Load XML
    objDom.async = False
    objDom.LoadXML XmlBody
    ' Open the webservice
    objXmlHttp.Open "POST", AsmxUrl, False
   
    ' Create headings
    objXmlHttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
    objXmlHttp.setRequestHeader "SOAPAction", SoapActionUrl
   
    ' Send XML command
    objXmlHttp.send objDom.XML
    ' Get all response text from webservice
    strRet = objXmlHttp.responseText
    MsgBox strRet
    ' Close object
    Set objXmlHttp = Nothing
   
    ' Extract result
    intPos1 = InStr(strRet, "Result>") + 7
    intPos2 = InStr(strRet, "</")
    If intPos1 > 7 And intPos2 > 0 Then
        strRet = Mid(strRet, intPos1, intPos2 - intPos1)
    End If
   
    ' Return result
    PostWebservice = strRet
   
Exit Function
Err_PW:
    PostWebservice = "Error: " & Err.Number & " - " & Err.Description
End Function

Wednesday 5 June 2013

VBA code to iterate through the results of GetListCollection web service from Sharepoint 2007

Render Content Type fields as a form in Sharepoint Web Part using c#

Render Content Type fields as a form in Sharepoint Web Part using c#

In this blog entry I will give you some example code that will render a simple form in a Sharepoint 2007 web part. The form fields are taken from a pre-defined Sharepoint Content Type. I struggled to find any examples of this on the net, despite it seeming to me to be a fairly ordinary thing to want to do (after all, if you go to all the trouble of defined your own Content Types to organise your data, surely you would want to use them in your own web parts?).

In order to develop this, I used C# / Visual Studio 2008 and Sharpoint 2007. This should also work in Visual Studio 2005, although you will have to install the web part manually - Visual Studio 2008 has far tighter links to Sharepoint, meaning debugging and deploying is much easier. It should also work in VS2010 / Sharepoint 2010.

The following method will return a SPContentType object, you only need to pass it a list name and content type name.  The SPContentType object can be used later to iterate through its fields in oder to render controls based on the content type's fields.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <summary>
/// Returns the content type object
/// </summary>
/// <param name="listName"></param>
/// <param name="contentTypeName"></param>
/// <returns></returns>
SPContentType ReadContentType(string listName, string contentTypeName)
{
  
    //get the web
    this._web = Microsoft.SharePoint.SPContext.Current.Web;
  
    SPList dirList = this._web.Lists[listName];
    SPContentType contentType = dirList.ContentTypes[contentTypeName];
  
    //You could simply iterate here like this if you wish, like this:
    //foreach (SPField field in _contentType.Fields)
    //{
    //    string dispName = field.Title;
    //    SPFieldType type = field.Type;
    //    object defaultValue = field.DefaultValue;
  
    //}
  
    return contentType;
}

The following code overrides the "CreateChildControls" Sharepoint method to create our own controls based on the content type.  In this example, only text fields and date-times are rendered, but hopefully it straight forward enough for you can see how you could extend this. Simply change: 
?
1
"Your_List_Name" and "Your_Content_Type_Name"
to your actual values from your Sharepoint site.
I use the "LiteralControl" method to render raw HTML on the page to format the form, which feels really nasty but is efective.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
protected override void CreateChildControls()
{
    //Controls.Clear();
    //base.CreateChildControls();
  
    // Read in the content type for the target list
    SPContentType contentType = ReadContentType("Your_List_Name", "Your_Content_Type_Name");
      
    Controls.Add(new LiteralControl("<TABLE>"));
  
    foreach (SPField field in contentType.Fields)
    {
        // Ignore hidden or readonly fields
        if (field.Hidden) continue;
        if (field.ReadOnlyField) continue;     
  
        if (field.Type == SPFieldType.Text)
        {
            string dispName = field.Title;
            string staticName = field.StaticName;
            SPFieldType type = field.Type;
            object defaultValue = field.DefaultValue;
  
            Controls.Add(new LiteralControl("<TR>"));
            Controls.Add(new LiteralControl("<TD>"));
            Label lbl = new Label();
            lbl.Text = dispName;
  
            Controls.Add(lbl);
  
            Controls.Add(new LiteralControl("</TD>"));
  
            // Textbox
            TextBox tb = new TextBox();
            // I give my controls a unique ID so I can reference them later
            tb.ID = "xx_ctl_xx" + dispName;
              
            if(defaultValue != null)
                tb.Text = defaultValue.ToString();
  
            Controls.Add(new LiteralControl("<TD>"));
            Controls.Add(tb);
            Controls.Add(new LiteralControl("</TD>"));
            Controls.Add(new LiteralControl("</TR>"));
  
        }
        else if (field.Type == SPFieldType.DateTime)
        {
              
            string dispName = field.Title;
            string staticName = field.StaticName;
            SPFieldType type = field.Type;
            object defaultValue = field.DefaultValue;
  
            Label lbl = new Label();
            lbl.Text = dispName;
  
            Controls.Add(new LiteralControl("<TR>"));
            Controls.Add(new LiteralControl("<TD>"));
            Controls.Add(lbl);
            Controls.Add(new LiteralControl("</TD>"));
  
            // Datetime picker
            SPDatePickerControl dtp = new SPDatePickerControl();
            dtp.ID = "xx_ctl_xx" + staticName;
             
            if (defaultValue != null)
                dtp.SelectedDate = defaultValue.ToString();
  
            Controls.Add(new LiteralControl("<TD>"));
            Controls.Add(dtp);
              
            Controls.Add(new LiteralControl("</TD>"));
            Controls.Add(new LiteralControl("</TR>"));
        }       
    }
    Controls.Add(new LiteralControl("</TABLE>"));
  
    //In my code, I use the controls to perform a custom search.  The following code plugs in
    //the event handler to do this, based on the values the user puts into the controls rendered above.
    //This blog post will not go into the detail of this so I have commented the following lines out.
    //cmdSearch = new Button();
    //cmdSearch.Text = "Start Search";
    //cmdSearch.Click += new EventHandler(cmdSearch_Click);
    //this.Controls.Add(cmdSearch);
  
    //lblQueryResult = new Label();                     
    //this.Controls.Add(lblQueryResult);
      
    base.CreateChildControls();
}

Once deployed, you can add this web part to your site in the normal way using the web front end.  Depending on the fields in your content type, it should render something like this (web part highlighted in pink):