In the current scenario I am trying to copy a document set from one library to another, the thing is I cant use DocumentSet.Import because I only need the docset properties and not the contents.
The exception is thrown in the System.Update of this code.
private void CopyAgendaPointToRootSite(SPListItem agendaPointItem, string oldReasonReturned)
{
try
{
if (agendaPointItem != null)
{
SPWeb currentSite = agendaPointItem.ParentList.ParentWeb;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(currentSite.Site.RootWeb.Url))
{
using (SPWeb elevatedTargetWeb = site.OpenWeb())
{
SPList targetList = GetAgendaPointProposedTargetLibrary(agendaPointItem, elevatedTargetWeb);
SPDocumentLibrary targetDocumentLibrary = (SPDocumentLibrary)targetList;
SPContentTypeId targetCTId = targetList.ContentTypes.BestMatch(new SPContentTypeId(MeetingsCommon.Constants.CONTENTTYPES_AGENDAPOINTPROPOSED_ID));
DocumentSet documentSet = DocumentSet.GetDocumentSet(agendaPointItem.Folder);
if (documentSet != null)
{
string strAgendaPointTitle = agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTTITLENL_NAME] +
" / " + agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTTITLEFR_NAME];
SPListItemCollection colProposedItems = FindAgendaPointProposedItem((SPDocumentLibrary)targetList, documentSet.Item.Name);
if (colProposedItems.Count > 0)
throw new Exception(string.Format(HelperFunctions.GetResourceString(
MeetingsCommon.Constants.RESOURCES_FILE_NAME,
"Message_AgendaPointsEvents_ERROR_DocumentSetAlreadyExistsInRootSite2"), strAgendaPointTitle));
using (DisableItemEventScope scope = new DisableItemEventScope())
{
DocumentSet docSetCreated = DocumentSet.Create(targetList.RootFolder, agendaPointItem.Name, targetCTId, new Hashtable(), true);
SPListItem listItem = docSetCreated.Item;
foreach (SPField field in agendaPointItem.Fields)
{
if (!field.ReadOnlyField && field.InternalName != "Attachments" && field.InternalName != "TaxCatchAll")
{
if (agendaPointItem[field.Id] != null)
{
string targetFieldInternalName = field.InternalName;
if (listItem.Fields.ContainsField(field.InternalName))
{
listItem[targetFieldInternalName] = agendaPointItem[field.InternalName];
}
}
}
}
string reasonreturned = "---- <br/>Reason returned: " + currentSite.Title + " Rejected. " + "<br/> "
+ agendaPointItem.GetTaxonomyFieldValueByLanguage(site, MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME, 1036) + "<br/> "
+ agendaPointItem.GetTaxonomyFieldValueByLanguage(site, MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME, 1043) + "<br/> "
+ agendaPointItem.GetFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISIONCOMMENTSNL_NAME)
+ agendaPointItem.GetFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISIONCOMMENTSFR_NAME)
+ agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSREASONRETURNED_NAME] + "<br/>----";
SPFieldUrlValue value = new SPFieldUrlValue();
value.Description = currentSite.Title;
value.Url = currentSite.Url;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTPOSTPONEDFROM_NAME] = value;
listItem[MeetingsCommon.Constants.FIELDS_MEETING_NAME] = null;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSTATUS_NAME] = null;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSREASONRETURNED_NAME] = reasonreturned;
//Clear the category and status field
listItem.ClearTaxonomyFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTSTATUS_NAME);
listItem.ClearTaxonomyFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME);
listItem.SystemUpdate(false);
}
}
}
}
});
}
}
catch (Exception ex)
{
throw;
}
}
I fixed it doing the following
DocumentSet docSetCreated = DocumentSet.Create(targetList.RootFolder, agendaPointItem.Name, targetCTId, new Hashtable(), true);
int listItemId = docSetCreated.Item.ID;
SPListItem listItem = targetList.GetItemById(listItemId);
apparently after the documentset is created, I cant use the listitem of that object anymore, I need to get a new one
Related
How can I ignore writing of records giving error while updating the entities.
ERROR DISPLAY
private void btn_salary_Click(object sender, EventArgs e)
{
if (sg.HasRows(lib.tbl_pay) == true && chkShowOnly.Checked == false)
{
lib.ShowMessage(lib.tbl_pay + " has data can not import");
return;
}
sql = "SELECT * FROM PAY WHERE BankAc IS NOT null";
q1 = new DBFHelper(txt_olddir.Text).FillDataTable(sql);
dataGridView1.DataSource = q1;
if (chkShowOnly.Checked == true) return;
DateTime xdate = sg.ServerDate;
for (int x = 0; x < q1.Rows.Count; x++)
{
PAY q11 = new PAY
{
BANKAC = sg.AsString(q1.Rows[x]["BankAc"]),
MDATE = sg.AsDate(q1.Rows[x]["MDATE"].ToString()),
BYEAR = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Year,
BMONTH = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Month,
PERPAY = q1.AsDecimal("PERPAY", x),
BASIC = q1.AsDecimal("PERPAY", x),
DARATE = q1.AsDecimal("DA", x),
NEWDA = q1.AsDecimal("NEWDA",x),
ADNDA = q1.AsDecimal ("ADNDA",x),
HRA = q1.AsDecimal ("HRA",x),
ENTREL = q1.AsDecimal("ENTREL",x),
EXTRA = q1.AsDecimal("EXTRA",x),
INSKNP = q1.AsDecimal("INSGKP",x),
MEDI = q1.AsDecimal("MEDI",x),
RD = q1.AsDecimal("RD",x),
GPF = q1.AsDecimal("GPF",x),
GPFLOAN= q1.AsDecimal("GPFLOAN",x),
CPF = q1.AsDecimal("CPF",x),
CPFLOAN = q1.AsDecimal("CPFLOAN",x),
LICPRE = q1.AsDecimal("LICPRE",x),
LICLOAN = q1.AsDecimal("LICLOAN",x),
ITAX = q1.AsDecimal("ITAX",x),
JSBLOAN = q1.AsDecimal("JSBLOAN",x),
NSBLOAN = q1.AsDecimal("NSBLOAN",x),
STEMP = q1.AsDecimal("STEMP",x),
PROFUND = q1.AsDecimal("PROFUND",x),
TYPE_ATX = q1.AsString("TYPE",x),
GRADE = q1.AsString("GRADE",x),
TFUND = q1.AsDecimal("TFUND",x),
GFUND = q1.AsDecimal("GFUND",x),
OBCLOAN = q1.AsDecimal("OBCLOAN",x),
OTH1_LOAN = q1.AsDecimal("OTH1_LOAN",x),
OTH2_LOAN = q1.AsDecimal("OTH2_LOAN",x),
BSTGBANK = q1.AsDecimal("BSTGBANK",x),
EARNING = q1.AsDecimal("EARNING",x),
TOTDED = q1.AsDecimal("TOTDED",x),
NETPAY = q1.AsDecimal("NETPAY",x),
CITYALW = q1.AsDecimal("CITYALW",x),
user_code = lib.user_code,
modi_dt = xdate
};
g1.PAYs.Add(q11);
lbl_counter.Text = x.ToString() + " Records Inserted";
Application.DoEvents();
}
try
{
g1.SaveChanges();
}
catch (Exception ex)
{
string emsg = ex.Message;
if (ex.InnerException != null)
{
emsg = emsg + ex.InnerException.Message;
}
if (ex.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.Message;
}
if (ex.InnerException.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.InnerException.Message;
}
lib.ShowMessage(emsg);
}
lib.ShowMessage("Done..");
}
I have created windows service scheduler which run after 24 hr, When i stared the service first time it enters data in database it run perfectly fine.
But in second run service get stops , however i want service run continually.
I have created scheduler for it as well to run it every minute , but data only inserts when time match .
public void StartService(object e)
{
try {
//ExtractorEventLog("0", null);
List<PracticeInformation> getServiceTime = GetpracticeInformationList();
var gettime = (from t in getServiceTime
select new PracticeInformation
{
extractor_start_time = t.extractor_start_time
}).OrderByDescending(x => x.id).ToList().FirstOrDefault();
DateTime SetdateTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]);
if (gettime != null)
{
SetdateTime = DateTime.Parse(gettime.extractor_start_time.ToString());
}
try
{
if (SetdateTime.ToString("HH:mm") == DateTime.Now.ToString("HH:mm"))
{
ExtractorEventLog(SetdateTime.ToString("HH:mm") + " " + DateTime.Now.ToString("HH:mm"), null);
string strFile = #"C:\requiredFilesForDDP\Temp" + DateTime.Now.Ticks.ToString() + ".csv";
if (connm == "")
{
GetConnectionString();
}
using (OdbcConnection conn = new OdbcConnection(connm))
{
//ExtractorEventLog(connm, null);
conn.Open();
#region Get Hospital data
var id = 0;
try
{
List<PracticeInformation> practiceList = getServiceTime;
var practiceName = practiceList[0].name;
id = practiceList[0].id;
List<PracticeInformationModel> HospitalAll = new List<PracticeInformationModel>();
using (OdbcCommand com = new OdbcCommand(Common.cmdGetHospital, conn))
{
using (OdbcDataReader readerHospital = com.ExecuteReader())
{
HospitalAll = DataReaderMapToList<PracticeInformationModel>(readerHospital);
List<PracticeInformationModel> objPracticeInformationmodel = (from pi in HospitalAll
select new PracticeInformationModel
{
practice_name = pi.practice_name,
phone = pi.phone
}
).ToList();
var getPracticeName = practiceList.Select(x => new { x.name }).ToList();
List<PracticeInformationModel> objpracticelist = objPracticeInformationmodel.Where(x => !getPracticeName.Any(y => y.name == x.practice_name)).ToList();
DataTable PracticeInformationDT = ToDataTable(objpracticelist); // To save PracticeInformation table
using (MySqlConnection sqConn = new MySqlConnection(Common.connectionStringDB))
{
using (SqlBulkCopy blkcopyPi = new SqlBulkCopy(sqConn.ConnectionString, SqlBulkCopyOptions.KeepNulls))
{
CreateCSVfile(PracticeInformationDT, strFile);
if (!File.Exists(strFile))
{
FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
fs.Close();
fs.Dispose();
}
if (sqConn.State == ConnectionState.Open)
{
sqConn.Close();
}
sqConn.Open();
MySqlBulkLoader bcp1 = new MySqlBulkLoader(sqConn);
bcp1.TableName = "PracticeInformation"; //Create PracticeInformation table into MYSQL database...
bcp1.FieldTerminator = ",";
bcp1.LineTerminator = "\r\n";
bcp1.FileName = strFile;
bcp1.NumberOfLinesToSkip = 0;
bcp1.Load();
try
{
File.Delete(strFile);
}
catch (Exception ex)
{
ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
}
}
readerHospital.Close();
}
}
}
#endregion
#region Get Provider Data From Dentrix
List<Provider> ProviderAll = new List<Provider>();
using (OdbcCommand com = new OdbcCommand(Common.cmdGetProvider, conn))
{
using (OdbcDataReader readerProvider = com.ExecuteReader())
{
ProviderAll = DataReaderMapToList<Provider>(readerProvider);
List<Provider> objProvider = (from pro in ProviderAll
select new Provider
{
provider_id = pro.provider_id,
first_name = pro.first_name,
last_name = pro.last_name,
work_phone = pro.work_phone
}).ToList();
}
}
#endregion
#region Add Appointment
using (OdbcCommand com = new OdbcCommand(Common.cmdText, conn))
{
using (OdbcDataReader reader = com.ExecuteReader())
{
List<AllModalFromApplointment> AppointmentListAll = new List<AllModalFromApplointment>();
AppointmentListAll = DataReaderMapToList<AllModalFromApplointment>(reader);
List<Alert> patientalert_id = new List<Alert>();
#region Get alert data
MySqlConnection connection = null;
List<string> target = new List<string>();
EventLog(Common.Get_Pre_Med_Alerts);
ExtractorEventLog(Common.Get_Pre_Med_Alerts, id.ToString());
int add = 0;
int alert_count = 0;
//string connectionStringDB = "server=192.168.0.1;user=dentrix;database=db_dentrix;password=dentrix";
connection = new MySqlConnection(Common.connectionStringDB);
foreach (var i in AppointmentListAll.Select(x => x.patient_id).ToList())
{
if (i != 0)
{
OdbcCommand ODBCCommand = new OdbcCommand("{call admin.sp_getpatientmedalerts (?)}", conn);
ODBCCommand.CommandType = CommandType.StoredProcedure;
ODBCCommand.Parameters.AddWithValue("#patient_guid", i); //4898-11738
ODBCCommand.ExecuteNonQuery();
OdbcDataReader a = ODBCCommand.ExecuteReader();
DataTable getAlert = new DataTable();
if (a.HasRows)
{
target.Add(i.ToString());
alert_count = add + 1;
getAlert.Load(a);
a.Close();
}
}
}
ExtractorEventLog(target.Count() + " " + Common.No_Of_Pre_Med_Alert, null);
#endregion
#region
List<AppointmentDetail> objAppointment = (from app in AppointmentListAll
join pro in ProviderAll on app.provider_id equals pro.provider_id
select new AppointmentDetail
{
patient_id = Convert.ToInt64(app.patient_guid),
appointment_id = Convert.ToInt64(app.appointment_id),
appointment_timestamp = Convert.ToString(app.appointment_date.AddHours(app.start_hour).AddMinutes(app.start_minute)),
patient_first_name = app.patient_name.Split(',')[0],
patient_last_name = app.patient_name.Split(',')[1],
patient_phone_number = app.patient_phone,
red_cross_flag = target.Any(x => x.ToString().Contains(app.patient_id.ToString())) ? "Y" : "N",
dr_name = pro.first_name.Trim() + ' ' + pro.last_name.Trim(),
dr_phone = HospitalAll[0].phone,
hospital_name = HospitalAll[0].practice_name,
appointment_type = null,
fees = 0,
status = null
//createdDate = DateTime.UtcNow
}).ToList();
//Ristrict duplicate records
ExtractorEventLog(Common.Data_Inserting, id.ToString());
List<AppointmentDetail> usethe = GetAppointmentList();
var query = usethe.Select(x => new { x.appointment_id }).ToList();
List<AppointmentDetail> xyz = objAppointment.Where(x => !query.Any(y => y.appointment_id == x.appointment_id)).ToList();
if (xyz != null && xyz.Count != 0)
{
var from = xyz.First().appointment_timestamp;
var to = xyz.Last().appointment_timestamp;
ExtractorEventLog(Common.Get_Appointment_Date + from + "and" + to, id.ToString());
}
else
{
EventLog("No appointmet present");
}
int appointment_count = xyz.Count();
DataTable appointmentDT = ToDataTable(xyz); // To save appointment table
using (MySqlConnection sqConn = new MySqlConnection(Common.connectionStringDB))
{
using (SqlBulkCopy blkcopy = new SqlBulkCopy(sqConn.ConnectionString, SqlBulkCopyOptions.KeepNulls))
{
CreateCSVfile(appointmentDT, strFile);
if (!File.Exists(strFile))
{
FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
fs.Close();
fs.Dispose();
}
if (sqConn.State == ConnectionState.Open)
{
sqConn.Close();
}
sqConn.Open();
MySqlBulkLoader bcp1 = new MySqlBulkLoader(sqConn);
bcp1.TableName = "appointment";
//bcp1.TableName = "Appointment"; //Create Appointment table into MYSQL database.
bcp1.FieldTerminator = ",";
bcp1.LineTerminator = "\r\n";
bcp1.FileName = strFile;
bcp1.NumberOfLinesToSkip = 0;
bcp1.Load();
try
{
File.Delete(strFile);
}
catch (Exception ex)
{
ExtractorEventLog("appointment-ex", null);
ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
}
ExtractorEventLog(appointment_count + " " + Common.No_Of_Appointment_Retrive, id.ToString());
}
ExtractorEventLog(Common.Done, id.ToString());
this.ScheduleService();
}
#endregion
}
}
}
catch (Exception ex)
{
ExtractorEventLog("a-ex", null);
ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
}
}
}
else{
this.ScheduleService();
}
}
catch (Exception ex)
{
ExtractorEventLog(ex.Message +"b-ex", null);
//ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
}
//EventLog("this ScheduleService()");
// this.ScheduleService();m
}
catch(Exception ex)
{
ExtractorEventLog("zz-ex", null);
}
}
I am having trouble handling nulls in my json file. As you can see in the following photo the null value is under player:
This unfortunately is causing the following InvalidOperationException:
System.InvalidOperationException: Cannot access child value on
Newtonsoft.Json.Linq.JValue.
at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
at WindowsFormsApplication2.Starting_Lineups.StartingLineups() in C:\Users\Administrator\documents\visual studio
2015\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Starting
Lineups.cs:line 97
I tried the following How to ignore a property in class if null, using json.net but have been unsuccessful.
JSON:
{"gamestartinglineup":{"lastUpdatedOn":"2017-10-24 11:41:12 AM","game":{"id":"42120","date":"2017-10-24","time":"7:30PM","awayTeam":{"ID":"83","City":"New York","Name":"Knicks","Abbreviation":"NYK"},"homeTeam":{"ID":"82","City":"Boston","Name":"Celtics","Abbreviation":"BOS"},"location":"TD Garden"},"teamLineup":[{"team":{"ID":"83","City":"New York","Name":"Knicks","Abbreviation":"NYK"},"expected":{"starter":[{"position":"Bench8","player":null},{"position":"Starter1","player":{"ID":"9087","LastName":"Hardaway Jr.","FirstName":"Tim","JerseyNumber":"3","Position":"SG"}},{"position":"Starter2","player":{"ID":"9373","LastName":"Porzingis","FirstName":"Kristaps","JerseyNumber":"6","Position":"PF"}},{"position":"Starter5","player":{"ID":"9518","LastName":"Sessions","FirstName":"Ramon","JerseyNumber":"1","Position":"PG"}},{"position":"Starter3","player":{"ID":"9396","LastName":"Kanter","FirstName":"Enes","JerseyNumber":"0","Position":"C"}},{"position":"Starter4","player":{"ID":"9127","LastName":"Lee","FirstName":"Courtney","JerseyNumber":"1","Position":"SG"}},{"position":"Bench1","player":{"ID":"9148","LastName":"McDermott","FirstName":"Doug","JerseyNumber":"20","Position":"SF"}},{"position":"Bench2","player":{"ID":"9376","LastName":"O'Quinn","FirstName":"Kyle","JerseyNumber":"9","Position":"PF"}},{"position":"Bench3","player":{"ID":"9245","LastName":"Beasley","FirstName":"Michael","JerseyNumber":"9","Position":"F"}},{"position":"Bench4","player":{"ID":"10102","LastName":"Baker","FirstName":"Ron","JerseyNumber":"31","Position":"G"}},{"position":"Bench5","player":null},{"position":"Bench6","player":null},{"position":"Bench7","player":null}]},"actual":null},{"team":{"ID":"82","City":"Boston","Name":"Celtics","Abbreviation":"BOS"},"expected":{"starter":[{"position":"Bench8","player":null},{"position":"Starter1","player":{"ID":"13730","LastName":"Tatum","FirstName":"Jayson","JerseyNumber":"0","Position":"F"}},{"position":"Starter2","player":{"ID":"9082","LastName":"Horford","FirstName":"Al","JerseyNumber":"15","Position":"C"}},{"position":"Starter5","player":{"ID":"9157","LastName":"Irving","FirstName":"Kyrie","JerseyNumber":"11","Position":"PG"}},{"position":"Starter3","player":{"ID":"9211","LastName":"Baynes","FirstName":"Aron","JerseyNumber":"12","Position":"C"}},{"position":"Starter4","player":{"ID":"10090","LastName":"Brown","FirstName":"Jaylen","JerseyNumber":"7","Position":"SF"}},{"position":"Bench1","player":{"ID":"13777","LastName":"Theis","FirstName":"Daniel","JerseyNumber":"27","Position":"PF"}},{"position":"Bench2","player":{"ID":"9105","LastName":"Rozier","FirstName":"Terry","JerseyNumber":"12","Position":"PG"}},{"position":"Bench3","player":{"ID":"13770","LastName":"Nader","FirstName":"Abdel","JerseyNumber":"28","Position":"SF"}},{"position":"Bench4","player":{"ID":"9120","LastName":"Larkin","FirstName":"Shane","JerseyNumber":"8","Position":"PG"}},{"position":"Bench5","player":{"ID":"13778","LastName":"Yabusele","FirstName":"Guerschon","JerseyNumber":"30","Position":"PF"}},{"position":"Bench6","player":{"ID":"13771","LastName":"Bird","FirstName":"Jabari","JerseyNumber":"26","Position":"SG"}},{"position":"Bench7","player":null}]},"actual":null}]}}
Code:
public void StartingLineups()
{
upass.upass up = new upass.upass();
string address3 = "https://api.mysportsfeeds.com/v1.1/pull/nba/2017-2018-regular/game_startinglineup.json?gameid=" + dateTimePicker1.Text + comboBox2.Text;
var w3 = new WebClient();
w3.UseDefaultCredentials = true;
w3.Credentials = new NetworkCredential(up.username, up.password);
var result3 = w3.DownloadString(address3);
var obj3 = JObject.Parse(result3);
StartingLineup.startinglineup sl = new StartingLineup.startinglineup();
try
{
foreach (JToken child in obj3 ["gamestartinglineup"]["teamLineup"])
{
foreach (JToken sub in child["expected"]["starter"])
{
JsonConvert.SerializeObject(sub,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
sl.player = sub["player"]["FirstName"].ToString() + " " + sub["player"]["LastName"].ToString();
sl.team = child["team"]["City"].ToString() + " " + child["team"]["Name"].ToString();
sl.position = sub["position"].ToString();
sl.playerpositon = sub["player"]["Position"].ToString();
DataRow row = dt.NewRow();
row["Team"] = sl.team;
row["Player"] = sl.player;
row["Position"] = sl.playerpositon;
if (sl.position.Contains("Starter"))
{
row["Role"] = sl.position;
}
else
{
row["Role"] = "NOPE";
}
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
DataRow[] drr = dt.Select("Role='NOPE'");
for (int i = 0; i < drr.Length; i++)
drr[i].Delete();
dt.AcceptChanges();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Consider this, when checking for nullable values (Value<T>(Object key)):
var testObj = new Newtonsoft.Json.Linq.JObject();
if (testObj.TryGetValue("player", out Newtonsoft.Json.Linq.JToken token)) {
string yourString = token.Value<string>("FirstName"); // can be null
int? yourNullableInt = token.Value<int?>("AnyNumber"); // can be null
int yourInt = token.Value<int?>("AnyNumber") ?? 0; // can be 0 if null
int yourInt = token.SelectToken("firstLayer")?.SelectToken("secondLayer")?.Value<int?>("anyNumber") ?? 0; // return value by path
}
SelectToken is also applicable on Newtonsoft.Json.Linq.JObject.
There is a row in gridview in which there is a column name as POA_NO whose value is 899.
But I am deleting that value and updating it as blank. But still it is getting updated as 899 only.
Here is my code
protected void GrdDetail_UpdateCommand(object sender, GridRecordEventArgs e)
{
if (Session["ViewInfo"] != null)
{
dtViewInfo = (DataTable)Session["ViewInfo"];
}
else
{
return;
}
DataRow[] drViewInfo = dtViewInfo.Select("SR_NO = " + e.Record["SR_NO"]);
if (e.Record["TYPE"] != "")
{
drViewInfo[0]["TYPE"] = e.Record["TYPE"];
}
else
{
drViewInfo[0]["TYPE"] = "NULL";
}
if (e.Record["REF_NO"] != "")
{
drViewInfo[0]["REF_NO"] = e.Record["REF_NO"];
}
if (e.Record["REF_DATE"] != "")
{
drViewInfo[0]["REF_DATE"] = e.Record["REF_DATE"];
}
if (e.Record["POA_NO"] != "")
{
drViewInfo[0]["POA_NO"] = e.Record["POA_NO"];
}
if (e.Record["POA_DATE"] != "")
{
drViewInfo[0]["POA_DATE"] = e.Record["POA_DATE"];
}
if (e.Record["POA_NAME"] != "")
{
drViewInfo[0]["POA_NAME"] = e.Record["POA_NAME"];
}
if (e.Record["ATTACHMENT"] != "")
{
drViewInfo[0]["ATTACHMENT"] = e.Record["ATTACHMENT"];
}
GrdDetail.DataSource = dtViewInfo;
GrdDetail.DataBind();
AddToViewState("GridViewInfo");
}
EDIT
Page load code
dtViewInfo = CF.ExecuteDT("select sr_no, type, ref_no, to_char (ref_date,'dd/MM/yyyy') ref_date, POA_NO , to_char (POA_DATE, 'dd/MM/yyyy') POA_DATE, POA_NAME, attachment from xxcus.XXACL_PN_VIEW_DATA_INFO " +
"where mkey = '" + StrMkey + "' order by sr_no");
GrdDetail.DataSource = dtViewInfo;
GrdDetail.DataBind();
AddToViewState("GridViewInfo");
I have a global DataTable named 'DTImageList' and an XtraGrid named 'uxImageGrid'. Now there is a Method named 'prcFillImagesVideosAndFiles' in which we bring image data from data base page wise i.e. say 500 rows at a time and we create mannual Pages on top of the Grid by using XtraTabControl depending on the total count of data exists according to search. Say if we get 700 Images then will load only 500 at a time and 2 pages will be created as 'Page 1', 'Page 2'.
But in 'prcFillImagesVideosAndFiles' method, we are not fetching the actual images but only its name, id etc. After this I created a new Thread and invoking a method runner which in turn calls a new method called 'FillImages' in which I look through DTImageList and bring actual image one by one from backend and update row with this image due to which XtraGrid starts showing images one by one.
This process works fine for few minutes i.e. loads 20-25 images and after that it gives 'Cross-thread operation not valid' error.
// My prcFillImagesVideosAndFiles method's Code is:
`if (DTImageList != null)
{
DTImageList.Rows.Clear(); DTImageList.Columns.Clear(); DTImageList = null;
}
string sql = #"select " + top + #" IM.Image_ID,IM.extension,IM.Is_Uploaded,cast(0 as varbinary) 'ActualImage',IM.description 'Description',IM.ContentType,IM.DateTime_Uploaded,IM.FolderName, '' as FilePath
from images as IM where IM.GCRecord is null and IM.Is_Uploaded=1 " + MainCriteria + #" " + Ob + #"";
string sql1 = LayoutPaging(sql);
DTImageList = new DataTable();
DTImageList = FillDataTable(sql1);
DataTable DTdeliv2 = new DataTable();
DTdeliv2.Columns.Add("Image");
DTdeliv2.Columns.Add("UniqueNumber");
DTdeliv2.Columns["Image"].DataType = typeof(Image);
DTdeliv2.Columns["UniqueNumber"].DataType = typeof(int);
DTImageList.Merge(DTdeliv2, true, MissingSchemaAction.Add);
uxImageGrid.DataSource = null;
uxImageGrid.DataSource = DTImageList;
RepositoryItemTextEdit riTextEdit = new RepositoryItemTextEdit();
riTextEdit.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
layoutView1.Columns["Description"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
riTextEdit.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
riTextEdit.Appearance.Options.UseBackColor = true;
riTextEdit.NullText = "";
uxImageGrid.RepositoryItems.Add(riTextEdit);
layoutView1.Columns["Description"].ColumnEdit = riTextEdit;
riTextEdit.Leave += new EventHandler(riTextEdit_Leave);
riTextEdit.KeyPress += new KeyPressEventHandler(riTextEdit_KeyPress);
RepositoryItemPictureEdit riPictureEdit = new RepositoryItemPictureEdit();
riPictureEdit.SizeMode = PictureSizeMode.Zoom;
riPictureEdit.ShowMenu = false;
riPictureEdit.NullText = " Loading Image";
riPictureEdit.Appearance.Image = Pionero.RetailTherapy.Properties.Resources.mag;
uxImageGrid.RepositoryItems.Add(riPictureEdit);
layoutView1.Columns["Image"].ColumnEdit = riPictureEdit;
riPictureEdit.MouseMove += new MouseEventHandler(riPictureEdit_MouseMove);
riPictureEdit.MouseDown += new MouseEventHandler(riPictureEdit_MouseDown);
layoutView1.Columns["Image"].Caption = "";
int k = DTImageList.Rows.Count;
if (k > 0)
{
DevExpress.Data.Filtering.CriteriaOperator expr1 = new DevExpress.Data.Filtering.BinaryOperator("Is_Uploaded", true);
layoutView1.ActiveFilterCriteria = expr1;
if (pthread != null)
{
StopRunningThread();
}
if (pthread == null || pthread.IsAlive==false)
{
pthread = new Thread(new ThreadStart(runner));
pthread.IsBackground = true;
Is_ThreadNeededtoWork = true;
pthread.Start();
}
else
{
Is_ThreadNeededtoWork = true;
pthread.Start();
}
}`
//The runner method is:
void runner()
{
if (Is_ThreadNeededtoWork == false)
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
return;
}
if (Is_ThreadNeededtoWork == true)
{
FillImages();
}
}
// FillImages method's code is:
try
{
if (DTImageList.Rows.Count <= 0) return;
StringBuilder sbImagesNotLoaded = new StringBuilder();
sbImagesNotLoaded.Append("Following images not loaded due to connection: ");
ArrayList lstImage_IDs = new ArrayList();
int NoOfAttempts = 0;
//if (dtImages != null)
//{
for (int i = 0; i < DTImageList.Rows.Count; i++)
{
NoOfAttempts = 0;
V:
string Qry = #" Select Image_ID,image from images where Image_ID = " + DTImageList.Rows[i]["Image_ID"].ToString();
dtImages = FillDataTable(Qry);
if (dtImages != null && dtImages.Rows.Count > 0)
{
if (DTImageList.Rows[i]["image"] == DBNull.Value)
{
// Thread.Sleep(100);
byte[] barr = (byte[])dtImages.Rows[0]["image"];
Image img = Global.byteArrayToImage(barr);
DTImageList.Rows[i]["Image"] = img;
DTImageList.AcceptChanges();
uxImageGrid.RefreshDataSource();
}
}
else
{
// Thread.Sleep(100);
if (Convert.ToInt32(DTImageList.Rows[i]["Image_ID"]) > 0)
if (NoOfAttempts < 3)
{
NoOfAttempts = NoOfAttempts + 1;
goto V;
}
else
{
if (lstImage_IDs.Count > 0)
sbImagesNotLoaded.Append("," + Convert.ToString(DTImageList.Rows[i]["Description"]));
else
sbImagesNotLoaded.Append(Convert.ToString(DTImageList.Rows[i]["Description"]));
lstImage_IDs.Add(DTImageList.Rows[i]["Image_ID"]);
}
}
}
//}
if (lstImage_IDs.Count > 0)
{
for (int i = 0; i < lstImage_IDs.Count; i++)
{
DataRow drImage = DTImageList.Select("Image_ID=" + Convert.ToString(lstImage_IDs[i]) + "").FirstOrDefault();
if (drImage != null)
DTImageList.Rows.Remove(drImage);
}
DTImageList.AcceptChanges();
XtraMessageBox.Show(sbImagesNotLoaded.ToString(), Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
EnableDisablePanelControls(true);
if (pthread != null)
{
Is_ThreadNeededtoWork = false;
StopRunningThread();
}
}
catch (ThreadAbortException abortException)
{
}
catch (Exception emmp)
{
EnableDisablePanelControls(true);
//pthread.Abort();
}
finally
{
//Global.StopProg();
}
//StopRunningThread() 's code is:
void StopRunningThread()
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
Is_ThreadNeededtoWork = false;
}
Thanks
Vicky
You can try inserting images before you pass it as Datasource to uxImageGrid.
Add image column to DTImageLis.
DTImageList.Columns.Add("Image", typeof(System.Drawing.Image));
Add the image to datatable based on Name,Id etc and bind it to uxImageGrid
uxImageGrid.Datasource=DTImageList;