c# Retrieve multiple XML child nodes - c#

I've managed to link up a single XElement successfully into my program though I'm not having any luck with the other two I have in place, I've tried using;
IEnumerable query = from booking in doc.Descendants("Booking")
Though I've haven't had much luck placing the values into list box.
Here's the code for function:
private void btnimport_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.CheckFileExists = true;
open.InitialDirectory = "#C:\\";
open.Filter = "XML Files (*.xml)|*.xml|All Files(*.*)|*.*";
open.Multiselect = false;
if (open.ShowDialog() == DialogResult.OK)
{
try
{
XDocument doc = XDocument.Load(open.FileName);
//Grabs the customer elements
var query = from booking in doc.Descendants("Booking")
select new
{
//Customer Elements
CustomerId = booking.Element("CustomerId").Value,
Title = booking.Element("Title").Value,
Firstname = booking.Element("FirstName").Value,
Lastname = booking.Element("LastName").Value,
DateofBirth = booking.Element("DateofBirth").Value,
Email = booking.Element("Email").Value,
HouseNo = booking.Element("HouseNo").Value,
Street = booking.Element("Street").Value,
Postcode = booking.Element("Postcode").Value,
Town = booking.Element("Town").Value,
County = booking.Element("County").Value,
ContactNo = booking.Element("ContactNo").Value,
//Holiday Elements
HolidayId = booking.Element("HolidayId").Value,
HotelName = booking.Element("HotelName").Value,
Location = booking.Element("Location").Value,
BookFrom = booking.Element("BookFrom").Value,
BookTo = booking.Element("BookTo").Value,
CheckInTime = booking.Element("CheckInTime").Value,
CheckOutTime = booking.Element("CheckOutTime").Value,
NoOfRoomsBooked = booking.Element("NoOfRoomsBooked").Value,
RoomType = booking.Element("RoomType").Value,
RoomServices = booking.Element("RoomServices").Value,
Parking = booking.Element("Parking").Value,
Pet = booking.Element("Pet").Value,
//TravelInfo Elements
TravelInfoId = booking.Element("TravelInfoId").Value,
TravellingFrom = booking.Element("TravellingFrom").Value,
Destination = booking.Element("Destination").Value,
Fare = booking.Element("Fare").Value,
TravelInsurance = booking.Element("TravelInsurance").Value,
InFlightMeals = booking.Element("In-FlightMeals").Value,
LuggageAllowance = booking.Element("LuggageAllowance").Value,
ExtraLuggage = booking.Element("ExtraLuggage").Value,
CarHire = booking.Element("CarHire").Value,
ReturnTransfer = booking.Element("ReturnTransfer").Value,
};
//Inputs all of the values in bookings
foreach (var booking in query)
{
//Customer values
txtCustomerId.Text = txtCustomerId.Text + booking.CustomerId;
txttitle.Text = txttitle.Text + booking.Title;
txtfname.Text = txtfname.Text + booking.Firstname;
txtlname.Text = txtlname.Text + booking.Lastname;
txtdob.Text = txtdob.Text + booking.DateofBirth;
txtemail.Text = txtemail.Text + booking.Email;
txthouseno.Text = txthouseno.Text + booking.HouseNo;
txtstreet.Text = txtstreet.Text + booking.Street;
txtpostcode.Text = txtpostcode.Text + booking.Postcode;
txttown.Text = txttown.Text + booking.Town;
txtcounty.Text = txtcounty.Text + booking.County;
txtcontactno.Text = txtcontactno.Text + booking.ContactNo;
//Holiday Values
txtHolidayId.Text = txtHolidayId.Text + booking.HolidayId;
txthname.Text = txthname.Text + booking.HotelName;
txtl.Text = txtl.Text + booking.Location;
txtbf.Text = txtbf.Text + booking.BookFrom;
txtbt.Text = txtbt.Text + booking.BookTo;
txtcit.Text = txtcit.Text + booking.CheckInTime;
txtcot.Text = txtcot.Text + booking.CheckOutTime;
txtnorb.Text = txtnorb.Text + booking.NoOfRoomsBooked;
txtrt.Text = txtrt.Text + booking.RoomType;
txtrs.Text = txtrs.Text + booking.RoomServices;
txtpark.Text = txtpark.Text + booking.Parking;
txtpet.Text = txtpet.Text + booking.Pet;
//TravelInfo Values
txtTravelInfoId.Text = txtTravelInfoId.Text + booking.TravelInfoId;
txttf.Text = txttf.Text + booking.TravellingFrom;
txtd.Text = txtd.Text + booking.Destination;
txtf.Text = txtf.Text + booking.Fare;
txtti.Text = txtti.Text + booking.TravelInsurance;
txtifi.Text = txtifi.Text + booking.InFlightMeals;
txtla.Text = txtla.Text + booking.LuggageAllowance;
txtel.Text = txtel.Text + booking.ExtraLuggage;
txtch.Text = txtch.Text + booking.CarHire;
txtrtrans.Text = txtrtrans.Text + booking.ReturnTransfer;
}
MessageBox.Show("XML has been imported");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If anyone knows where I've gone wrong or what I need to add / change please let me know :)
Many thanks,
10gez10

You have several problems:
Firstly, your data elements are not immediate children of the booking element, there are intermediate elements <Customer>, <Holiday> and <TravelInfo>. Thus you need to do something like
var query = from booking in doc.Descendants("Booking")
let customer = booking.Element("Customer")
let holiday = booking.Element("Holiday")
let travelInfo = booking.Element("TravelInfo")
select new
{
//Customer Elements
CustomerId = customer.Element("CustomerId").Value,
Title = customer.Element("Title").Value,
HolidayId = holiday.Element("HolidayId").Value,
TravelInfoId = travelInfo.Element("TravelInfoId").Value,
}
Secondly, several elements are misspelled:
CheckOutTime should be CheckoutTime
In-FlightMeals should be InFlightMeals.
CarHire should be CareHire (yes "CareHire" is what's in the XML.)
Thus, when you do (e.g.) Element("In-FlightMeals").Value, Element() is returning null so you get a null reference exception and your code is aborted.
Thirdly, the element BookTo is completely missing, so BookTo = holiday.Element("BookTo").Value generates a null reference exception.
More generally, I do not recommend this coding approach. If any of your XML elements are missing, your query will throw an exception because element.Element("name") will be null. What's worse, Visual Studio doesn't seem to report an accurate line number on which the null reference occurs, instead giving the line number of the select new statement. And (on my version at least), it's not possible to step into the constructor for an anonymous type either. This makes debugging well-nigh impossible.
Instead, skip the intermediate anonymous type and do things in a more direct, traditional manner:
foreach (var booking in doc.Descendants("Booking"))
{
var customer = booking.Element("Customer");
var holiday = booking.Element("Holiday");
var travelInfo = booking.Element("TravelInfo");
XElement element;
if (customer != null)
{
if ((element = customer.Element("CustomerId")) != null)
txtCustomerId.Text = txtCustomerId.Text + element.Value;
}
// And so on.
}

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

Increase the amount of data on listview when the data is successfully stored in sqlite in uwp

I have a listview whose data comes from a sqlite database. The database is created when the user selects the list on the previous page whose data comes from JSON.
Code:
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
loading.IsIndeterminate = true;
try
{
string urlPath = "https://.../tryout_perid";
var httpClient = new HttpClient(new HttpClientHandler());
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("tid", ((App)(App.Current)).ID)
};
var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
loading.IsIndeterminate = false;
RequestException();
}
string jsonText = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonText);
JsonArray jsonData = jsonObject["data"].GetArray();
foreach (JsonValue groupValue1 in jsonData)
{
JsonObject groupObject2 = groupValue1.GetObject();
string id = groupObject2["id"].GetString();
string title = groupObject2["judul"].GetString();
QuizHome quiz = new QuizHome();
quiz.ID = id;
((App)(App.Current)).ID = quiz.ID.ToString();
quiz.Title = title;
quizDataSource.Add(quiz);
if (quizDataSource.Count > 0)
{
string InsertQuiz = #"INSERT INTO DBName (ID,Judul) SELECT '" + id.ToString() + "','" + title.ToString() + "','" + "' WHERE not exists " +
"(select ID and Judul FROM DBName WHERE ID='" + id.ToString() + "' and Judul='" + title.ToString() + "')";
var quizName = objConn.Prepare(InsertQuiz);
quizName.Step();
}
JsonArray jsonDataSoal = groupObject2["list_soal"].GetArray();
foreach (JsonValue groupValueSoal in jsonDataSoal)
{
JsonObject groupObjectSoal = groupValueSoal.GetObject();
string qid = groupObjectSoal["qid"].GetString();
string pertanyaan = groupObjectSoal["question"].GetString();
QuizQuestion question = new QuizQuestion();
question.QID = qid;
question.Pertanyaan = pertanyaan;
questionDataSource.Add(question);
if (questionDataSource.Count > 0)
{
string InsertQuestion = #"INSERT INTO DBQuestion (QID,Pertanyaan) SELECT '" + qid.ToString() + "','" + pertanyaan.ToString() + "' WHERE not exists " +
"(select QID and Pertanyaan FROM DBQuestion WHERE OID='" + qid.ToString() + "' and Pertanyaan='" + pertanyaan.ToString() + "')";
var quizQuestion = objConn.Prepare(InsertQuestion);
quizQuestion.Step();
}
JsonArray jsonDataOption = groupObjectSoal["jawaban"].GetArray();
foreach (JsonValue groupValueOption in jsonDataOption)
{
JsonObject groupObjectOption = groupValueOption.GetObject();
string oid = groupObjectOption["oid"].GetString();
string option = groupObjectOption["q_option"].GetString();
string score = groupObjectOption["score"].GetString();
QuizOption pilihan = new QuizOption();
pilihan.OID = oid;
pilihan.Option = option;
optionDataSource.Add(pilihan);
if (optionDataSource.Count > 0)
{
string InsertOption = #"INSERT INTO DBOption (OID,Option) SELECT '" + oid.ToString() + "','" + option.ToString() + "','" + "' WHERE not exists " +
"(select OID and Option FROM DBOption WHERE OID='" + oid.ToString() + "' and Option='" + option.ToString() + "')";
var quizOption = objConn.Prepare(InsertOption);
quizOption.Step();
}
}
}
this.Loaded += ReadTryoutList_Loaded;
loading.IsIndeterminate = false;
}
}
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
ListTryout.ItemsSource = DB_TryoutList.OrderByDescending(i => i.ID).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
if (DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
I am having problems, that is when the user selects the list on the previous page and the data is successfully stored in the database, but the amount of data on listview is not increased. If I click the back button and enter on this page again, then the data on listview increases. How do I get listview to increase in the number of data when the data is successfully saved?
This issue is caused by the asynchronous method in your code. After you click the item, you navigate to the TryoutLibrary1 page. On this page, you save the data to the database meanwhile you get the data source from the database on the Page.Loaded event. But when you get the data, the clicked item has not been insert into the database, so it will not display on the page until you reload the data(reenter the page again).
So you should reconsider your logic again in the ItemClick event, you should make sure the data have saved into the database then you get and set the data as the ListView.ItemsSource. As a example, when you click the item, you can create a object and put it into a local ObservableCollection object, then set the ObservableCollection as the ListView itemsSource to make it display on the UI, on other side, you save the item to the database.

Nested Linq conversion (select)

Im trying to convert an object (Lead) to a reduced form of the same object (ApiLead)
The object contains a list of objects (OtherInHousehold) which also needs to be reduced (ApiOtherInHousehold):
result = leads.Select(lead => new ApiLead()
{
UserId = lead.UserId,
DepartmentId = lead.DepartmentId,
CompanyId = lead.CompanyId,
CPR_number = lead.CPR_number,
CVR_number = lead.CVR_number,
Name = (lead.FirstName == "[virksomhed]" ? "" : lead.FirstName + " ") + lead.LastName,
Address = (lead.Street + " " + lead.StreetNumber + " " + lead.Floor + " " + lead.Side).Trim(),
Zipcode = lead.Zipcode,
City = (lead.PlaceName + " " + lead.City).Trim(),
Phonenumber = ("Fastnet: " + lead.Phonenumber + " Mobil: " + lead.Cellphonenumber),
Email = lead.Email,
BestReached = lead.BestReached,
**OthersInHousehold = lead.OthersInHousehold.Select(oih => new ApiOtherInHousehold(){ CPR_number = oih.CPR_number, Name = oih.Name }).ToList()**,
WantsVisit = lead.WantsVisit,
WantsPhonecall = lead.WantsPhonecall,
WantsInsuranceImmediately = lead.WantsInsuranceImmediately,
ExistingInsurance = lead.ExistingInsurance,
CurrentInsuranceCompany = lead.CurrentInsuranceCompany,
OtherInfo = lead.OtherInfo,
Status = lead.Status,
CreationDate = lead.CreationDate
}).ToList();
But this throws an
Cannot implicitly convert type 'System.Collections.Generic.List<LeadsApp.ApiModels.ApiLead>' to
'System.Collections.Generic.List<LeadsApp.Models.Lead>'
Is this not possible or am I doing it wrong?
Thanks, guys.
At the linq statement, you are returning List<ApiLead>. But result variable is List<Lead>. You have to declare your result variable as List<ApiLead>.
Hope helps,

How do I access a tasks collection on user stories using Rally .NET toolkit?

I get:
Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given
key was not present in the dictionary.
when iterating over user story query results and try to access story["Tasks"]
foreach (var story in queryStoryResults.Results)
{
Console.WriteLine("FormattedID: " + story["FormattedID"]);
Console.WriteLine("Name: " + story["Name"]);
Console.Write("Tasks: " + story["Tasks"]);
}
First, make sure that Tasks are being fetched, along with task specific fields that you want to extract, e.g. State.
Next, a nested loop is needed inside the loop that iterates over user story results.
Here is the code example. It queries on user stories from the current iteration and prints out FormattedID and State of tasks associated with the query results:
namespace RESTexample_storiesFromIteration
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#domain.com", "1984", "https://rally1.rallydev.com", "1.43");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/1111";
String projectRef = "/project/2222";
bool projectScopingUp = false;
bool projectScopingDown = true;
DateTime now = DateTime.Today;
String nowString = now.ToString("yyyy-MM-dd");
Request iterationRequest = new Request("Iteration");
iterationRequest.Workspace = workspaceRef;
iterationRequest.Project = projectRef;
iterationRequest.Fetch = new List<string>()
{
"Name",
"StartDate",
"EndDate",
"Project",
"State"
};
String iterationQueryString = "((StartDate <= \"" + nowString + "\") AND (EndDate >= \"" + nowString + "\"))";
iterationRequest.Query = new Query(iterationQueryString);
QueryResult queryIterationResults = restApi.Query(iterationRequest);
var myIteration = queryIterationResults.Results.First();
var myIterationName = myIteration["Name"];
var myIterationProject = myIteration["Project"];
var myIterationProjectName = myIterationProject["Name"];
Console.WriteLine("Name: " + myIterationName);
Console.WriteLine("Project Ref: " + myIterationProjectName);
Console.WriteLine("State: " + myIteration["State"]);
// Query for Stories
Request storyRequest = new Request("hierarchicalrequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"ObjectID",
"ScheduleState",
"State",
"FormattedID",
"PlanEstimate",
"Iteration",
"Tasks"
};
storyRequest.Query = new Query("Iteration.Name", Query.Operator.Equals, myIterationName);
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine("----------");
Console.WriteLine("FormattedID: " + s["FormattedID"]);
Console.WriteLine("Name: " + s["Name"]);
Console.WriteLine("PlanEstimate: " + s["PlanEstimate"]);
var tasks = s["Tasks"];
foreach (var t in tasks)
{
Console.WriteLine("Task: " + t["FormattedID"] + " " + t["State"]);
}
}
}
}
}

Add lookup field to list from a RootWeb

I have the site collection rootweb called Main Site.
I have many subsites called according to the year, 2012, 2011, etc.
In the rootweb, there is a list called Products.
In the subsites there is a list called Sales, and I need to add a lookup field to the list Products in the root site.
I found this code, but its not working, it created the lookup field, but the dropdown is empty even if there are products.
//Request North lookup
currentList = currentWeb.GetSafeListByName(SponsoringCommon.Constants.LISTNAMES_SALESNORTH);
string sFldReqNr = SponsoringCommon.Constants.FIELDS_REQUESTNUMBERLOOKUPNORTH_NAME + currentWeb.Title;
Functions.CreateRequestNumberLookup(currentList, sFldReqNr, false, Functions.NorthSouth.North);
ArrayList colPreviousContentTypes = new ArrayList();
currentList.AddFieldToContentType(sFldReqNr, SponsoringCommon.Constants.CONTENTTYPES_SALESNUMBER_NAME, 2, colPreviousContentTypes, 1033);
public static void CreateProductNameLookup(SPList currentList, string strInternalFieldName, bool allowMultipleValues)
{
Logger.LogDebug("Functions",
"CreateProductNameLookup(SPList currentList, string strInternalFieldName, bool allowMultipleValues)", "BEGIN");
SPWeb currentWeb = currentList.ParentWeb;
SPList targetList = currentWeb.Site.RootWeb.GetSafeListByName(SponsoringCommon.Constants.LISTNAMES_PRODUCT_NAME);
SPFieldCollection colFields = currentList.Fields;
Guid targetListID = targetList.ID;
int L1 = strInternalFieldName.Length;
int L2 = currentWeb.Title.Length;
string sFieldNameWithoutYear = (strInternalFieldName.EndsWith(currentWeb.Title) ?
strInternalFieldName.Substring(0, L1 - L2) :
strInternalFieldName);
if (colFields.ContainsField(strInternalFieldName))
{
Logger.LogDebug("Functions",
"CreateProductNameLookup(SPList currentList, string strInternalFieldName, bool allowMultipleValues)",
"Field '" + strInternalFieldName + "' already exists. (>> Skipped)");
}
else
{
strInternalFieldName = colFields.AddLookup(strInternalFieldName, targetListID, false);
SPField fld = colFields.GetFieldByInternalName(strInternalFieldName);
fld.ShowInNewForm = true;
fld.ShowInEditForm = true;
fld.ShowInDisplayForm = true;
SPFieldLookup fldLU = fld as SPFieldLookup;
fldLU.AllowMultipleValues = allowMultipleValues;
string strSchemaXml = fldLU.SchemaXmlWithResourceTokens;
strSchemaXml = strSchemaXml.Replace("DisplayName=\"" + strInternalFieldName + "\"", "DisplayName=\"$Resources:SPNLSponsoring,Field_" + sFieldNameWithoutYear + "_Name;\"");
strSchemaXml = strSchemaXml.Replace("/>", " ShowField=\"" + targetList.Fields[SponsoringCommon.Constants.FIELDS_PRODUCT_NAMENEW].InternalName + "\" " +
"Description=\"$Resources:SPNLSponsoring,Field_" + sFieldNameWithoutYear + "_Description;\" " +
"Group=\"$Resources:SPNLSponsoring,Field_NationaleLoterijSponsoringColumns_Group;\" />");
fldLU.SchemaXml = strSchemaXml;
fldLU.Update(true);
currentList.Update();
}
Logger.LogDebug("Functions",
"CreateProductNameLookup(SPList currentList, string strInternalFieldName, bool allowMultipleValues)", "END");
}
its possible, I already solved it, I had to use another overload of the method addlookup that receives the parentweb.id
strInternalFieldName = colFields.AddLookup(strInternalFieldName, targetListID, currentWeb.Site.RootWeb.ID, true);
then it works fine

Categories