How to get the datatype of column from the sharepoint list? - sharepoint-2010

I want to get or retrieve the datatype of a particular column where
the list is created in a sharepoint list.
Can you help me for doing the task?

See SPField.Type (or SPField.TypeDisplayName).
SPList list = web.Lists["my list"];
SPField field = list.Fields["particular"];
SPFieldType fieldType = field.Type;
string fieldTypeName = field.TypeDisplayName;

Building off of Rich Bennema's answer (referencing the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.RunTime version 16 libriaries and using the Microsoft.SharePoint.Client name space):
using (ClientContext cont = new ClientContext(SharePointUrl))
{
cont.Credentials = new SharePointOnlineCredentials(Username, SecurePassword);
FieldCollection fields = cont.Web.Lists.GetByTitle(SharePointListName).Fields;
cont.Load(fields);
cont.ExecuteQuery();
var results =
fields.Select(
f => new
{
f.InternalName,
f.TypeDisplayName,
TextMaxLength = (f is FieldText) ? ((FieldText)f).MaxLength : 0,
FieldChoices = (f is FieldChoice) ? ((FieldChoice)f).Choices : new string[0]
}
);
}

Related

ASP.Net Core SelectList not displaying selected item

Using ASP.Net core 2.2 in VS 2017 (MVC):
I have a wizard based screen that has a drop down list of Organizations.
When I load a record from the Database, I want to set the select list to the values in the DB.
Spoiler alert: The specified Item is not selected when the page is initially displayed.
When the item is manually selected, and the ‘Next’ button is clicked and then the Prev button is clicked, returning us to the first page, the item is selected just as I intend.
None of the methods below set the ‘Selected’ property of the selected item (“0403”) when loading the Model in the controller for the first display.
The compare in Method 2 never evaluates to true even though I can see the compared values are equal while debugging.
Method 3 does not find the item even though I can see the compared values are equal while debugging
Method 4 does not find the item even though I can see the compared values are equal while debugging
This is all happening in the Controller, so please do not suggest changing the name of the dropdown in the View.
**Org table
ORG ID OrgName**
0004 Org 4
0007 Org 7
0008 Org 8
0403 Org 403
This is my source query:
var orgsQuery = from s in _context.Orgs
orderby s.OrgID
select s;
These are the various ways I have tried building the select List in the Controller:
1).
SelectList oList = new SelectList(orgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
2).
List<SelectListItem> oList = new List<SelectListItem>();
foreach ( var item in OrgsQuery)
{
oList.Add(new SelectListItem()
{
Text = item.OrgName,
Value = item.OrgID,
Selected = (item.OrgID == (string)selectedOrg ? true : false)
});
}
3).
if (selectedOrg != null)
{
oList = new SelectList(OrgsQuery.AsNoTracking(),"OrgID", "OrgName", OrgsQuery.First(s =>
s.OrgID == (string)selectedOrg));
}
else
{
oList = new SelectList(OrgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
}
4).
SelectList oList =
new SelectList(_context.Org.OrderBy(r => r.OrgID),
_context.Org.SingleOrDefault(s => s.OrgID == (string)selectedOrg))
Well, assume that selectedOrg type is numeric, than it should be convert to formatted string by following the OrgID format:
var formattedSelectedOrg = String.Format("{0:0000}", selectedOrg);
Or
// if selectedOrg is nullable numeric type
var formattedSelectedOrg = selectedOrg?.ToString("0000");
// if selectedOrg is base numeric type
var formattedSelectedOrg = selectedOrg.ToString("0000");
// if selectedOrg is String type (nullable)
var formattedSelectedOrg = selectedOrg?.Trim().PadLeft(4, '0');
Or
var number;
var formattedSelectedOrg =
String.Format("{0:0000}", Int32.TryParse(selectedOrg?.Trim(), out number) ? number : 0);
So it would be comparable when applied to your codes:
// assume selectedOrg is base numeric type
Selected = item.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
Selected = item.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
Selected = item.OrgID == formattedSelectedOrg
And
// assume selectedOrg is base numeric type
s => s.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
s => s.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
s => s.OrgID == formattedSelectedOrg
Check this out:
Custom numeric format strings
String.PadLeft Method
Also this important briefcase:
Pad left with zeroes
Hope this could helps. Enjoy your coding!

automated mapping in groovy for ODI with expression

this is my first question and I hope you can help me. I make a script in Groovy (in Oracle Data Integrator 12c) to automate mappings. Here is the description of my prodecure:
1 step: removing old mapping if exists.
2 step: looking for the project and the folder (if doesn't exist: create new one).
3 step: create new mapping
4 step: implement source and target table
5 step: create expression
6 step: link every column
Now my question: Can someone help me to make this script with a dynamic expression? Like this:
step 1: get the data types of the target columns
step 2: get the right data types into the expression
step 3: change the false types (always Varchar) into the right types (Number or Date or still Varchar)
step 4: link every column
My handicap: I have never done something with groovy and in Java I'm not very good. So it is not possible for me to make this dynamic. Almost everything in my Script is placed together from some internet sites. It would be great to find some guys who know something about my problem. And I think it would be a good script for all who will change from OWB to ODI.
Thanks!
//Von ODI Studio erstellt
//
//name of the project
projectName = "SRC_TO_TRG"
//name of the folder
ordnerName = "FEN_TEST"
//name of the mapping
mappingName = "MAP1_FF_TO_TRG"
//name of the model
modelName = "DB_FEN"
//name of the source datastore
sourceDatastoreName = "SRC_TEST_FEN"
//name of the target datastore
targetDatastoreName = "TRG_TEST_FEN"
import oracle.odi.domain.project.finder.IOdiProjectFinder
import oracle.odi.domain.model.finder.IOdiDataStoreFinder
import oracle.odi.domain.project.finder.IOdiFolderFinder
import oracle.odi.domain.project.finder.IOdiKMFinder
import oracle.odi.domain.mapping.finder.IMappingFinder
import oracle.odi.domain.adapter.project.IKnowledgeModule.ProcessingType
import oracle.odi.domain.model.OdiDataStore
import oracle.odi.core.persistence.transaction.support.DefaultTransactionDefinition
//set expression to the component
def createExp(comp, tgtTable, propertyName, expressionText) {
DatastoreComponent.findAttributeForColumn(comp,tgtTable.getColumn(propertyName)) .setExpressionText(expressionText)
}
//delete mapping with the same name
def removeMapping(folder, map_name) {
txnDef = new DefaultTransactionDefinition()
tm = odiInstance.getTransactionManager()
tme = odiInstance.getTransactionalEntityManager()
txnStatus = tm.getTransaction(txnDef)
try {
Mapping map = ((IMappingFinder) tme.getFinder(Mapping.class)).findByName(folder, map_name)
if (map != null) {
odiInstance.getTransactionalEntityManager().remove(map);
}
} catch (Exception e) {e.printStackTrace();}
tm.commit(txnStatus)
}
//looking for a project and folder
def find_folder(project_code, folder_name) {
txnDef = new DefaultTransactionDefinition()
tm = odiInstance.getTransactionManager()
tme = odiInstance.getTransactionalEntityManager()
txnStatus = tm.getTransaction(txnDef)
pf = (IOdiProjectFinder)tme.getFinder(OdiProject.class)
ff = (IOdiFolderFinder)tme.getFinder(OdiFolder.class)
project = pf.findByCode(project_code)
//if there is no project, create new one
if (project == null) {
project = new OdiProject(project_code, project_code)
tme.persist(project)
}
//if there is no folder, create new one
folderColl = ff.findByName(folder_name, project_code)
OdiFolder folder = null
if (folderColl.size() == 1)
folder = folderColl.iterator().next()
if (folder == null) {
folder = new OdiFolder(project, folder_name)
tme.persist(folder)
}
tm.commit(txnStatus)
return folder
}
//name of the project and the folder
folder = find_folder(projectName,ordnerName)
//delete old mapping
removeMapping(folder, mappingName)
txnDef = new DefaultTransactionDefinition()
tm = odiInstance.getTransactionManager()
tme = odiInstance.getTransactionalEntityManager()
txnStatus = tm.getTransaction(txnDef)
dsf = (IOdiDataStoreFinder)tme.getFinder(OdiDataStore.class)
mapf = (IMappingFinder) tme.getFinder(Mapping.class)
//create new mapping
map = new Mapping(mappingName, folder);
tme.persist(map)
//insert source table
boundTo_emp = dsf.findByName(sourceDatastoreName, modelName)
comp_emp = new DatastoreComponent(map, boundTo_emp)
//insert target table
boundTo_tgtemp = dsf.findByName(targetDatastoreName, modelName)
comp_tgtemp = new DatastoreComponent(map, boundTo_tgtemp)
//create expression-operator
comp_expression = new ExpressionComponent(map, "EXPRESSION")
// define expression
comp_expression.addExpression("LAND_KM", "TO_NUMBER(SRC_TEST_FEN.LAND_KM)", null,null,null);
comp_expression.addExpression("DATE_OF_ELECTION", "TO_DATE(SRC_TEST_FEN.DATE_OF_ELECTION, 'DD.MM.YYYY')", null,null,null);
//weitere Transformationen anhängen möglich
//link source table with expression
comp_emp.connectTo(comp_expression)
//link expression with target table
comp_expression.connectTo(comp_tgtemp)
createExp(comp_tgtemp, boundTo_tgtemp, "ABBR", "SRC_TEST_FEN.ABBR")
createExp(comp_tgtemp, boundTo_tgtemp, "NAME", "SRC_TEST_FEN.NAME")
createExp(comp_tgtemp, boundTo_tgtemp, "LAND_KM", "EXPRESSION.LAND_KM")
createExp(comp_tgtemp, boundTo_tgtemp, "DATE_OF_ELECTION", "EXPRESSION.DATE_OF_ELECTION")
tme.persist(map)
tm.commit(txnStatus)
You can pass the Datatype as the third argument of the method addExpression.
You can also pass the size and the scale as fourth and fifth arguments.
For instance, for the LAND_KM expression, replace your line by this :
MapAttribute map_attr = DatastoreComponent.findAttributeForColumn(comp_tgtemp,boundTo_tgtemp.getColumn("LAND_KM"))
comp_expression.addExpression("LAND_KM", "TO_NUMBER(SRC_TEST_FEN.LAND_KM)", map_attr.getDataType(),map_attr.getSize(),map_attr.getScale());
It retrieves the target column for LAND_KM thanks to findAttributeForColumn, then retrieves the datatype, the size and the scale, and use that when adding the new expression in the Expression component.
If you want to auto map it based on the name, David Allan wrote a post on the official Oracle blog about how to do it and he provides his code : https://blogs.oracle.com/dataintegration/entry/odi_12c_mapping_sdk_auto

Orchard - Creating Query Programmatically

I am creating a custom module in Orchard. After I enable my module I would like to create a query programmatically.
I do that in my Migrations.cs file thanks to implementation of IDependency interface.
I am able to create the query but I do I programmatically set filters of that query?
var announcementsQuery = _contentManager.Create("Query");
announcementsQuery.As<TitlePart>().Title = "Announcements";
_contentManager.Publish(announcementsQuery);
I found out how to do this:
var announcementsQuery = _contentManager.Create("Query");
announcementsQuery.As<TitlePart>().Title = "Announcements";
announcementsQuery.As<QueryPart>().ContentItem.ContentType = "Announcement";
var filterGroupRecord = new FilterGroupRecord();
var filterRecord = new FilterRecord()
{
Category = "Content",
Type = "ContentTypes",
Description = "Announcement",
Position = 1,
State = "<Form><Description>Announcement</Description><ContentTypes>Announcement</ContentTypes></Form>"
};
filterGroupRecord.Filters.Insert(0, filterRecord);
announcementsQuery.As<QueryPart>().FilterGroups.Insert(0, filterGroupRecord);

Get the lookup field value for a list item in SharePoint 2010 using C#

I am relatively new to sharepoint and I'm trying to write a web service to return our sharepoint inventory data as xml. It works good except that one of those list includes a lookup field and the generated xml contains "Microsoft.SharePoint.Client.FieldLookupValue" instead of the expected string value of the lookup field.
This is the code I'm using to generate the xml:
resultList = remoteWeb.Lists.GetByTitle("Cam Devices");
context.Load(resultList);
context.ExecuteQuery();
//Now its time to reach list's items
items = resultList.GetItems(new CamlQuery());
context.Load(items);
context.ExecuteQuery();
foreach (ListItem item in items)
{
rootNode.AppendChild(doc.CreateElement("ID")).InnerText = "pcat:401824";
rootNode.AppendChild(doc.CreateElement("Category")).InnerText = "Cam Devices";
rootNode.AppendChild(doc.CreateElement("Kimlik")).InnerText = Convert.ToString(item["ID"]);
rootNode.AppendChild(doc.CreateElement("Isim")).InnerText = Convert.ToString(item["Location0"]) + " >> " + Convert.ToString(item["Brand"]) + " >> " + Convert.ToString(item["ID"]);
}
item["Location"] is the lookup field and it has a value with the type FieldLookupValue, how can I get the lookup value as a string?
Ok, successfully get the lookup field's value by using following code syntax:
string Location = "";
if (item["Location0"] != null)
{
var fl = (SPFieldLookupValue)item["Location0"];
Location = fl.LookupValue;
}

SharePoint get value of rich text box control created programatically

I'm writing a custom web part that need to use a couple of rich text box controls. I'm placing the controls onto the web part programatically. When the web part gets a save postback I'm able to capture the data from all the fields except the two rich text box ones. What's the trick to be able to get the value of a rich text box?
The code I"m using to place my form controls is:
private void CreateInputControls()
{
inputPanel.Controls.Clear();
SPList list = SPContext.Current.Site.RootWeb.Lists["MyList"];
SPContentType cType = list.ContentTypes[0];
Table table = new Table();
table.CellPadding = 3;
table.CellSpacing = 0;
SPContext newContext = SPContext.GetContext(System.Web.HttpContext.Current, list.DefaultView.ID, list.ID, list.ParentWeb);
foreach (SPField field in cType.Fields)
{
if (!field.Hidden && field.CanBeDisplayedInEditForm)
{
FieldLabel fieldLabel = new FieldLabel();
fieldLabel.ControlMode = SPControlMode.New;
fieldLabel.ListId = list.ID;
fieldLabel.FieldName = field.InternalName;
fieldLabel.ItemContext = newContext;
fieldLabel.RenderContext = newContext;
fieldLabel.Field.Required = fieldLabel.Field.Required;
FormField formField = new FormField();
formField.ControlMode = SPControlMode.New;
formField.ListId = list.ID;
formField.FieldName = field.InternalName;
formField.ItemContext = newContext;
formField.RenderContext = newContext;
formField.ID = field.InternalName;
formField.EnableViewState = true;
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cellLabel = new TableCell();
TableCell cellField = new TableCell();
cellLabel.Controls.Add(fieldLabel);
cellField.Controls.Add(formField);
row.Cells.Add(cellLabel);
row.Cells.Add(cellField);
}
}
inputPanel.Controls.Add(table);
}
The code I'm using to save a new item is:
private void UpdateItem(string bannerImageURL, string thumbnailImageURL)
{
SPList list = SPContext.Current.Site.RootWeb.Lists["MyList"];
SPContentType cType = list.ContentTypes[0];
SPItem item = list.AddItem();
foreach (SPField field in cType.Fields)
{
if (!field.Hidden && field.CanBeDisplayedInEditForm)
{
FormField formField = (FormField)inputPanel.FindControl(field.InternalName);
if (formField != null)
{
// Saves data for all fields EXCEPT for rich text box (sharepoint multiline columns).
item[field.Title] = formField.Value;
}
}
}
item.Update();
}
Maybe there's an issue with the field name. Try to use the InternalName.
item[field.InternalName] = formField.Value;
I have been struggling with this and am using a workaround which I thought I'd post as this was quite frustrating.
The problem is that the RTE control is rendered empty and then populated from a hidden control with JavaScript on the client. However this hidden control is accessible server side thus:
switch (formField.Field.Type)
{
case SPFieldType.Note:
var rtf = (RichTextField)formField.Controls[0];
item[field.Title] = rtf.HiddenInput.Value;
break;
default:
item[field.Title] = formField.Value;
break;
}
This may need extending for other field types but you get the idea...