Check each List item if Null - c#

I am quite poor at writing code, hence the question. Below I am adding items into a SharePoint List from a DB while checking if any of the fields contains DBNulls. Rather than having to perform the check for each column like I am below, can someone help me to put it in a loop if possible? I would be forever grateful
using (OdbcConnection connection = new OdbcConnection())
{
connection.ConnectionString = "dsn=abc;uid=xyz;pwd=yuo;DataSource=aaa";
connection.ConnectionTimeout = 100;
connection.Open();
OdbcCommand command_donor = new OdbcCommand("Select * From vw_SP_aaa_bbb", connection);
try
{
using (OdbcDataReader reader = command_donor.ExecuteReader())
{
while (reader.Read())
{
var obj0 = reader.GetValue(48);
var obj1 = reader.GetValue(0);
var obj2 = reader.GetValue(33);
var obj3 = reader.GetValue(47);
var obj4 = reader.GetValue(42);
var obj5 = reader.GetValue(42);
ListItem oListItem_aaa = oList_aaa .AddItem(itemCreateInfo);
if (obj0 == null || obj0.Equals(DBNull.Value))
{ oListItem_aaa["Title"] = ""; }
else
{ oListItem_aaa["Title"] = reader.GetString(48).ToString(); }
if (obj1 == null || obj1.Equals(DBNull.Value))
{ oListItem_aaa["aaa_x0020_ID"] = ""; }
else
{ oListItem_aaa["aaa_x0020_ID"] = reader.GetString(0).ToString(); }
if (obj2 == null || obj2.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_By"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_By"] = reader.GetString(33).ToString(); }
if (obj3 == null || obj3.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_On"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_On"] = reader.GetDateTime(47).ToString("MM/dd/yyyy"); }
if (obj4 == null || obj4.Equals(DBNull.Value))
{ oListItem_aaa["Reason"] = ""; }
else
{ oListItem_aaa["Reason"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length-50); }
if (obj5 == null || obj5.Equals(DBNull.Value))
{ oListItem_aaa["Publish"] = ""; }
else
{ oListItem_aaa["Publish"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length - 50); }
oListItem_aaa.Update();
context.ExecuteQuery();
}
}
}
catch (Exception exception)
{
Console.WriteLine("The Error is:" + exception);
Console.ReadLine();
}
}

Use Short IIF like
oListItem_aaa["Excluded_x0020_By"] = (obj1 == null || obj1.Equals(DBNull.Value)) ? "" : reader.GetString(0).ToString();
or
var obj0 = (reader.GetValue(48) != DBNull.Value && !String.IsNullOrEmpty(Convert.ToString(reader.GetValue(48)))) ? reader.GetValue(48) : "");
in one line. Then you dont need to use the if then else's... described also in MSDN at Operator ?: (C#-Referenz).

Related

SAP.Middleware.Connector.RfcInvalidParameterException: Table line 0 out of range: table is empty

I have a C# console aplication that connects to a SAP server to get data from some of its tables.
Sometimes this error pops up when i try to copy a value from a field in a SAP table called "SOHEADER" to a string variable.
Here's the stack trace:
SAP.Middleware.Connector.RfcInvalidParameterException: Table line 0
out of range: table is empty en
SAP.Middleware.Connector.RfcTable.get_Item(Int32 lineIndex) en
ExportarPedidosSAP.Program.ControlFacturasRemitosNotasCreditos(RfcDestination
rfcDest, String& nroerror) en
C:\Users\USER\Source\repos\BSCPY\BSCPY\ExportarPedidosSAP\Program.cs:línea
1220 en ExportarPedidosSAP.Program.ConnSAPNotasCreditos() en
C:\Users\USER\Source\repos\BSCPY\BSCPY\ExportarPedidosSAP\Program.cs:línea
936
Here is the ControlFacturasRemitosNotasCreditos function:
static void ControlFacturasRemitosNotasCreditos(RfcDestination rfcDest, out string nroerror)
{
Console.WriteLine("** Controlando remitos... ");
nroerror = "";
using (SqlBriefcaseCropScience db = new SqlBriefcaseCropScience())
{
using (var transaction = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot }))
{
List<NotaCreditoCabecera> lstpedidos = new List<NotaCreditoCabecera>();
List<NotaCreditoItem> lstItemProducto = new List<NotaCreditoItem>();
IQueryable<NotaCreditoCabecera> ilstpedidos = null;
IQueryable<Compania> ilstcompanias = null;
List<NotaCreditoItem> lstprod = null;
NotaCreditoItem itProd = null;
int statuscode = 0;
decimal FKIMG = 0;
string ProdCode = "";
string statusdesc = "";
string status_doc = "";
string LEGALNUMBER = "";
string LEGALNUMBER_DEL = "";
bool savecabecera = false;
bool nolegalnumber = false;
bool itemfacturado = false;
bool pedidofacturado = false;
List<string> List_LEGALNUMBER_DEL = new List<string>();
List<string> List_LEGALNUMBER = new List<string>();
ilstcompanias = db.Compania;
DateTime unmes = Helpers.GetCurrentDateTime().AddMonths(1);
if (ilstcompanias != null)
{
foreach (Compania comp in ilstcompanias.ToList())
{
ilstpedidos = db.NotaCreditoCabecera.Where(c => c.CodigoCompania == comp.Codigo &&
(c.CodigoEstado == 5 || c.CodigoEstado == 11 && (DbFunctions.TruncateTime(c.FechaEstado) <= DbFunctions.TruncateTime(unmes))));
if (ilstpedidos != null)
{
lstpedidos = ilstpedidos.ToList<NotaCreditoCabecera>();
if (lstpedidos.Count() > 0)
{
RfcRepository rfcRep = rfcDest.Repository;
var funcionStatus = ConfigurationManager.AppSettings["SAP-RFC-Status"];
foreach (NotaCreditoCabecera cabecera in lstpedidos.ToList())
{
lstprod = db.NotaCreditoItem.Where(c => c.CodigoCompania == comp.Codigo && c.NroPedido == cabecera.NroPedido).ToList();
IRfcFunction functionStatus = rfcRep.CreateFunction(funcionStatus);
functionStatus.SetValue("SEL_ORDERSTATUS", "X");
functionStatus.SetValue("P_VKORG", cabecera.SalesOrg);
functionStatus.SetValue("P_BRIEFDOC", cabecera.NroPedido);
IRfcTable tableHstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaH-Status"]);
IRfcTable tableIstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaI-Status"]);
IRfcTable tablaEstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaE"]);
functionStatus.Invoke(rfcDest);
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
itemfacturado = false;
pedidofacturado = false;
nolegalnumber = false;
if (tableIstatus.RowCount > 0)
{
for (int e = 0; e < tableIstatus.RowCount; e++)
{
if (Convert.ToString(tableIstatus[e].GetValue("NETWR")) != "")
{
ProdCode = Convert.ToString(tableIstatus[e].GetValue("MATERIAL"));
itProd = lstprod.FirstOrDefault(i => i.CodigoProducto == ProdCode);
if (itProd != null)
{
//Num Factura
LEGALNUMBER = Convert.ToString(tableIstatus[e].GetValue("LEGALNUMBER")).Trim();
if (!String.IsNullOrEmpty(LEGALNUMBER))
{
itemfacturado = true;
//Num Remito
LEGALNUMBER_DEL = Convert.ToString(tableIstatus[e].GetValue("LEGALNUMBER_DEL")).Trim();
//Cantidad
FKIMG = (decimal.TryParse(Convert.ToString(tableIstatus[e].GetValue("FKIMG")), out FKIMG) == true) ?
Convert.ToDecimal(Convert.ToString(tableIstatus[e].GetValue("FKIMG"))) : 0;
//Si algun item no esta completamente facturado se considera el pedido no facturado
if ((LEGALNUMBER != "" && LEGALNUMBER_DEL != "") && (itProd.CantidadDevolucion == Convert.ToDecimal(FKIMG)) && (nolegalnumber == false))
{
pedidofacturado = true;
}
else
{
pedidofacturado = false;
break;
}
}
else
{
nolegalnumber = true;
}
}
}
}
//statuscode = 0;
//if (itemfacturado == true)
//{
// if (pedidofacturado == true)
// {
// statuscode = 12;
// }
//}
//if (statuscode > 0)
//{
// statusdesc = repositorioAdm.CEstado(cabecera.IdTipoOrden, statuscode);
// int reslog = ALogAutorizacion(db, transaction, cabecera.CodigoCompania,
// cabecera.SalesOrg, cabecera.CodigoDivision,
// cabecera.IdTipoOrden, cabecera.TipoOrden,
// cabecera.NroPedido.ToString(),
// cabecera.CodigoEstado.ToString(), cabecera.Estado,
// statuscode.ToString(), statusdesc, "inter", "");
// cabecera.CodigoEstado = statuscode;
// cabecera.Estado = statusdesc;
// cabecera.FechaEstado = Helpers.GetCurrentDateTime();
// savecabecera = true;
//}
}
//Tabla de Error
if (tablaEstatus.RowCount > 0)
{
//Obtengo el Estado
statuscode = 9;
cabecera.CodigoEstado = statuscode;
statusdesc = repositorioAdm.CEstado(cabecera.IdTipoOrden, statuscode);
cabecera.Estado = statusdesc;
cabecera.FechaEstado = Helpers.GetCurrentDateTime();
savecabecera = true;
int reslog = ALogAutorizacion(db, transaction, cabecera.CodigoCompania,
cabecera.SalesOrg, cabecera.CodigoDivision,
cabecera.IdTipoOrden, cabecera.TipoOrden,
cabecera.NroPedido.ToString(),
cabecera.CodigoEstado.ToString(),
cabecera.Estado,
statuscode.ToString(),
statusdesc, "inter", "");
}
}
}
}
if (savecabecera)
{
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
}
transaction.Complete();
}
}
}
}
}
Line 1220 inside ControlFacturasRemitosNotasCreditos:
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
Line 936 inside ConnSAPNotasCreditos that calls the ControlFacturasRemitosNotasCreditos function:
ControlFacturasRemitosNotasCreditos(rfcDest, out nroerror);
Can somebodoy tell me what could be the issue here? Could it be that the field comes empty from the SAP table and if i try to copy it somewhere the whole thing crashes? Is there a safe way to check if the field is null before trying to copy it?
in your line
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
you are adressing the IRfcTable tableHstatus with index 0, which means you're trying to read the first entry from that table object. That only works if the table has entries. You should first check whether the table contains any rows and only then continue. After invoking the RFC function, check property RowCount of your IRfcTable.
functionStatus.Invoke(rfcDest);
if (tableHstatus.RowCount > 0) {
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
}
there's a number of reasons why a RFC function might return an empty table. It could be standard behavior in some cases, or it could be because some query parameter was wrong and no data was found, or because an error occurred in the function. Standard SAP BAPIs usually return a status structure or table (often of type BAPIRETURN or BAPIRET2) that contains additional information about error codes, messages etc.

how can I add or update values with select count (*) and parameters SQL table and c#?

I'm trying to update information in the SQL table with this code using c# language, the first section is to count all data. the second section is to run my update Query/function
the event is : private void mlnk_ADD_Click(object sender, EventArgs e)
string SARL;
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [employe] WHERE CODE = #CODE OR FULLNAME =
#FULLNAME OR BIRTHDATE = #BIRTHDATE OR BIRTHPLACE = #BIRTHPLACE OR ADDRESS = #ADDRESS
OR NCCP = #NCCP OR PHONE = #PHONE OR JOB = #JOB OR SARL =#SARL", napster.myConn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#CODE", mtb_CODE.Text);
cmd.Parameters.AddWithValue("#FULLNAME", mtb_FULLNAME.Text);
cmd.Parameters.AddWithValue("#BIRTHDATE", mdtp_BIRTHDATE.Text);
cmd.Parameters.AddWithValue("#BIRTHPLACE", mtb_BIRTHPLACE.Text);
cmd.Parameters.AddWithValue("#ADDRESS", mtb_ADDRESS.Text);
cmd.Parameters.AddWithValue("#NCCP", mtb_NCCP.Text);
cmd.Parameters.AddWithValue("#PHONE", mtb_PHONE.Text);
cmd.Parameters.AddWithValue("#JOB", mtb_JOB.Text);
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
cmd.Parameters.AddWithValue("#SARL", SARL);
int UserExist = (int)cmd.ExecuteScalar();
here I am trying to insert the data into my table after checking that all data not exist to avoid the duplicate
if (UserExist > 0)
{
this.Alert("the information already exists.", frmAlert.alertTypeEnum.Error);
}
else
{
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
if (mtb_CODE.Text != "" && mtb_FULLNAME.Text != "" && mdtp_BIRTHDATE.Text != "" && mtb_BIRTHPLACE.Text != "" && mtb_JOB.Text != "" && mtb_PHONE.Text != "")
{
// (update_employee) is public void for insert data into [employe] table
napster.update_employee(mlnk_ID.Text, mtb_CODE.Text, mtb_FULLNAME.Text, mdtp_BIRTHDATE.Text, mtb_BIRTHPLACE.Text, mtb_ADDRESS.Text, mtb_JOB.Text, mtb_PHONE.Text, SARL, mtb_NCCP.Text);
mlnk_ID.Text = "";
mtb_CODE.Text = "";
mtb_FULLNAME.Text = "";
mdtp_BIRTHDATE.Text = "";
mtb_BIRTHPLACE.Text = "";
mtb_ADDRESS.Text = "";
mtb_JOB.Text = "";
mtb_PHONE.Text = "";
mtb_NCCP.Text = "";
mrb_LOCATERR.Checked = true;
this.Alert("information updated.", frmAlert.alertTypeEnum.Info);
}
else
{
this.Alert("information not updated.", frmAlert.alertTypeEnum.Error);
}
}
Use stored procedure its more cleanner and you can define the output and the input parameteres ( exemple :select cout(*) into output_parameter where ....).
and use switch statement, There is a lot of IF in your code.

I have a scenario I am unable to understand, regarding the session variables

Note:-The Question pertains to ASP.NET and C#.
I have 3 functions
GetDataBySearchCriteria.
GetData.
GetGridData.
The first function is called when page is loaded. The second function gets called when the user makes a change on page and and presses a btn (GetData) where I set the Session Variable which holds the Search Criteria Data as GridData Object. The Third function is called by the second function to get data as a GridData Object where GridData is a user defined class. Later in the calling function it is converted to json object which is used to render a grid table(jqgrid).
Problem:- We maintain the session in order to facilitate a temporary search criteria holder which we use when the intended user navigates from one page to another in the same module. In my code I set the Session variable only when user presses GetData and according to the current requirement I had to put hard code changes to change the data I get from session for particular pages. In doing so the Session Data is automatically changing. I am unable to figure out why. please help.
Here's the code :-
[System.Web.Services.WebMethod]
public static string GetDataBySearchCriteria(int ReportID) // called when page is loaded
{
if (SessionVariables.RoleID == 0)
{
return "null";
}
try
{
SetProperties(ReportID);
if (!CheckAuthorization(ReportID)) // write ! before statement after testing if its not written
{
return "null";
}
else
{
#region else part
HttpContext.Current.Session["ReportID"] = ReportID;
if (HttpContext.Current.Session["SalesUserSession"] != null)
{
SetProperties(ReportID);
GridData gd = new GridData();
gd = HttpContext.Current.Session["SalesUserSession"] as GridData;
if (pagetitle.ToLower() == "top referring practices")
{
gd.RowArea = "Referring Practice";
gd.order = "Month13#desc";
gd.SelectedCpt = "";
gd.SelectedLocation = "";
gd.SelectedModality = "";
gd.SelectedReferringPractice = "";
gd.SelectedPhysicians = "";
//gd.direction = "desc";
}
else if (pagetitle.ToLower() == "top referring physicians")
{
gd.RowArea = "Physician";
gd.order = "Month13#desc";
gd.SelectedCpt = "";
gd.SelectedLocation = "";
gd.SelectedModality = "";
gd.SelectedReferringPractice = "";
gd.SelectedPhysicians = "";
//gd.direction = "desc";
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(GetGridData(isVolume: gd.IsVolume, pageNumber: 1, pageSize: gd.PageSize, rowArea: gd.RowArea, cpt: gd.SelectedCpt, referringPhysician: gd.SelectedPhysicians, referringPractice: gd.SelectedReferringPractice, speciality: gd.SelectedSpeciality, modalityFilter: gd.SelectedModality, locationFilter: gd.SelectedLocation, practice: gd.SelectedPractice,order:gd.order,orderBy:gd.orderBy,direction:gd.direction,orderBySummary:gd.orderBySummary,OrderBySummaryCol:gd.orderBySummaryCol,ShowSubTotalForAllGroup: gd.ShowSubTotalForAllGroup));//,direction:gd.direction,orderBySummary:"",OrderBySummaryCol:""));
}
else
{
SqlParameter[] parameters = new SqlParameter[3]; // Error Line
parameters[0] = new SqlParameter("#UserId", SqlDbType.Int);
parameters[0].Value = SessionVariables.UserID;
parameters[1] = new SqlParameter("#RoleID", SqlDbType.Int);
parameters[1].Value = SessionVariables.RoleID;
parameters[2] = new SqlParameter("#ReportTitle", SqlDbType.NVarChar);
// Below Code Added on 11/05/2015 (dd/mm/yyyy) for Testing Purposes
//if (pagetitle == "Top Referring Practices" || pagetitle == "Top Referring Physicians")
//{
// //pagetitle = "Trending Report";
//}
// Modification Ends 11/05/2015
parameters[2].Value = pagetitle;
GridData gridData = new GridData();
DataSet ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.StoredProcedure, "Sales_GetDataByDefaultSearch", parameters);
DataTable Datadt = ds.Tables[1];
if (ReportID == 1 && ds.Tables.Count > 3)
{
//holidayList = ds.Tables[3].AsEnumerable().Select(r=>r.Field<string>("NonWorkingDays")).ToArray();
}
StringBuilder sbcol = new StringBuilder();
sbcol.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
sbcol.Append("\"").Append(GetPivotColumnName(column.ColumnName)).Append("\",");
}
sbcol.Remove(sbcol.Length - 1, 1).Append("]");
StringBuilder sbcolModel = new StringBuilder();
sbcolModel.Append("[");
string[] rowAreaFields = ds.Tables[0].Rows[0]["RowArea"].ToString().Split(',');
//string rowArea;
//rowArea = string.Join(",", rowAreaFields);
foreach (DataColumn column in Datadt.Columns)
{
//if (rowAreaFields.Contains(column.ColumnName.Trim()) && column.ColumnName != null)
if (rowAreaFields.Any(s => column.ColumnName.Trim().Contains(s)))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"sortable\":true,\"frozen\":true},");
}
//else if (holidayList.Contains(column.ColumnName.Trim()) && column.ColumnName != null)
//{
// sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"holidaystyle\",\"align\":\"right\",\"width\":\"70px\"},");
//}
else if (column.Ordinal >= Datadt.Columns.Count - NoofSummaryColumns)
{
if (PosNegSummaryValues.Contains(Datadt.Columns.Count - column.Ordinal))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"PosNegValue\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
if (column.ColumnName.Contains(" Actual"))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"120px\"},");
}
}
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"align\":\"right\",\"width\":\"70px\"},");
}
}
sbcolModel.Remove(sbcolModel.Length - 1, 1);
sbcolModel.Append("]");
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> drow;
foreach (DataRow dr in Datadt.Rows)
{
drow = new Dictionary<string, object>();
foreach (DataColumn col in Datadt.Columns)
{
drow.Add(GetPivotColumnName(col.ColumnName), dr[col]);
}
rows.Add(drow);
}
StringBuilder sbjsonRows = new StringBuilder();
sbjsonRows.Append(serializer.Serialize(rows));
StringBuilder json = new StringBuilder();
json.Append("{").Append("\"rows\":").Append(sbjsonRows.ToString().Trim()).Append("}");
json.ToString();
string[] GroupAreaSortOrderArray;
string[] SummarySortOrderArray;
foreach (DataRow dr in ds.Tables[0].Rows)
{
gridData.isReportDefault = dr["IsDefault"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsDefault"]);
gridData.isAllReportDefault = dr["IsAllReportDefault"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsAllReportDefault"]);
gridData.IsVolume = dr["IsVolume"] == DBNull.Value ? true : Convert.ToBoolean(dr["IsVolume"]);
gridData.RowArea = dr["RowArea"] == DBNull.Value ? "Modality" : GetRowAreaForPivot(Convert.ToString(dr["RowArea"]));
gridData.TitleName = dr["TitleName"] == DBNull.Value ? "" : Convert.ToString(dr["TitleName"]);
gridData.SelectedPractice = dr["PracticeFilter"] == DBNull.Value ? "" : Convert.ToString(dr["PracticeFilter"]);
gridData.SelectedModality = dr["ModalityFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ModalityFilter"]).Replace("'","");
gridData.SelectedLocation = dr["LocationFilter"] == DBNull.Value ? "" : Convert.ToString(dr["LocationFilter"]);
gridData.SelectedCpt = dr["CptFilter"] == DBNull.Value ? "" : Convert.ToString(dr["CptFilter"]).Replace("'","");
gridData.SelectedPhysicians = dr["ReferringPhysicianFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ReferringPhysicianFilter"]);
gridData.SelectedReferringPractice = dr["ReferringPracticeFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ReferringPracticeFilter"]);
gridData.SelectedSpeciality = dr["SpecialityFilter"] == DBNull.Value ? "" : Convert.ToString(dr["SpecialityFilter"]);
gridData.PageSize = dr["PageSize"] == DBNull.Value ? 30 : Convert.ToInt32(dr["PageSize"]);
gridData.ScheduledReport = dr["IsReportScheduled"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsReportScheduled"]);
gridData.Daily = dr["Daily"] == DBNull.Value ? false : Convert.ToBoolean(dr["Daily"]);
gridData.Weekly = dr["Weekly"] == DBNull.Value ? -1 : Convert.ToInt32(dr["Weekly"]);
gridData.Monthly = dr["Monthly"] == DBNull.Value ? 0 : Convert.ToInt32(dr["Monthly"]);
gridData.SelectedPracticeName = dr["PracticeName"] == DBNull.Value ? "" : Convert.ToString(dr["PracticeName"]);
gridData.ShowSubTotalForAllGroup = dr["ShowSubTotalForAllGroup"] == DBNull.Value ? "False" : Convert.ToString(dr["ShowSubTotalForAllGroup"]);
//remap the db column to its corresponding Pivot column here
GroupAreaSortOrderArray = Convert.ToString(dr["GroupAreaSortOrder"]).Split('#');
SummarySortOrderArray = Convert.ToString(dr["SummarySortOrder"]).Split('#');
gridData.order = dr["order"] == DBNull.Value ? "" : Convert.ToString(dr["order"]);
if (GroupAreaSortOrderArray[0] != "")
{
gridData.orderBy = GroupAreaSortOrderArray[0] == null ? "" : MapDbColumnsToPivot(GroupAreaSortOrderArray[0], Datadt);
gridData.direction = GroupAreaSortOrderArray[1] == null ? "" : MapDbColumnsToPivot(GroupAreaSortOrderArray[1], Datadt);
}
if (SummarySortOrderArray[0] != "")
{
gridData.orderBySummary = SummarySortOrderArray[0] == null ? "" : MapDbColumnsToPivot(SummarySortOrderArray[0], Datadt);
gridData.orderBySummaryCol = SummarySortOrderArray[1] == null ? "" : MapDbColumnsToPivot(SummarySortOrderArray[1], Datadt);
}
//gridData.orderBy = gridData.order == "" ? "" :gridData.order.Split('#')[0];
//gridData.direction = gridData.direction==""?"" :gridData.order.Split('#')[1];
//gridData.Date = dr["Date"] == DBNull.Value ? "" : Convert.ToDateTime(dr["Date"]).ToString("yyyy-MM-dd");
}
gridData.page = 1;
gridData.total = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(ds.Tables[2].Rows[0][0]) / Convert.ToDouble(ds.Tables[0].Rows[0]["PageSize"])));
gridData.records = Convert.ToInt32(ds.Tables[2].Rows[0][0]);
gridData.col = sbcol.ToString();
gridData.colModel = sbcolModel.ToString();
gridData.rows = sbjsonRows.ToString().Trim();
return serializer.Serialize(gridData);
}
#endregion
//}
}
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
[System.Web.Services.WebMethod]
public static string GetData(bool isVolume, int pageNumber, int pageSize, string rowArea, string specialityFilter, string modalityFilter, string locationFilter, string CptFilters, string referringpracticeFilter, string referringphysiciansFilter, int ReportID, string practiceFilter, string order, string orderBy, string direction, int SearchTitleID, string orderBySummary, string orderBySummaryCol, string ShowSubTotalForAllGroup)
{
try
{
if (HttpContext.Current.Session["RoleID"] == null || SessionVariables.RoleID == 0 || SessionVariables.UserID == 0)
{
return "null";
}
else
{
if (practiceFilter == null || practiceFilter == "")
{
practiceFilter = "1";
}
System.Collections.SortedList SystemSearchTitleIDs = new System.Collections.SortedList();
SystemSearchTitleIDs = (System.Collections.SortedList)HttpContext.Current.Session["SystemSearchTitleIds"];
SetProperties(ReportID);
HttpContext.Current.Session["ReportID"] = ReportID;
GridData gd;
string[] orderArray;
if (order.Trim() != string.Empty)
{
orderArray = order.Split('#');
orderArray[0] = SalesColumnMapper(orderArray[0]);
order = orderArray[0] + "#" + orderArray[1];
}
gd = GetGridData(isVolume: isVolume, pageNumber: pageNumber, pageSize: pageSize, rowArea: rowArea, modalityFilter: modalityFilter, locationFilter: locationFilter, referringPhysician: referringphysiciansFilter, referringPractice: referringpracticeFilter, speciality: specialityFilter, cpt: CptFilters, practice: practiceFilter, order: order, orderBy: orderBy, direction: direction, orderBySummary: orderBySummary, OrderBySummaryCol: orderBySummaryCol, ShowSubTotalForAllGroup: ShowSubTotalForAllGroup);
HttpContext.Current.Session["SalesUserSession"] = gd;
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(gd);
}
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
private static GridData GetGridData(bool isVolume, int pageNumber, int pageSize, string rowArea, string modalityFilter, string locationFilter, string referringPhysician, string referringPractice, string speciality, string cpt, string practice, string order,string orderBy, string direction, string orderBySummary, string OrderBySummaryCol,string ShowSubTotalForAllGroup)
{
try
{
string[] rowAreaFields = rowArea.Split(',').Select(field => field.Trim()).ToArray();
DataSet ds = GetDataByFilterCriteria(isVolume: isVolume, pageNumber: pageNumber, pageSize: pageSize, rowArea: rowArea, modalityFilter: modalityFilter, locationFilter: locationFilter, referringPhysician: referringPhysician, referringPractice: referringPractice, speciality: speciality, cpt: cpt, practice: practice, order: order, ShowSubTotalForAllGroup: ShowSubTotalForAllGroup);
DataTable Datadt = ds.Tables[0];
StringBuilder sbcol = new StringBuilder();
sbcol.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
sbcol.Append("\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",");
}
sbcol.Remove(sbcol.Length - 1, 1);
sbcol.Append("]");
StringBuilder sbcolModel = new StringBuilder();
sbcolModel.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
if (rowAreaFields.Any(s => GetPivotColumnName(column.ColumnName.Trim()).Contains(s)))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"sortable\":true,\"frozen\":true},");
}
else if (column.Ordinal >= Datadt.Columns.Count - NoofSummaryColumns)
{
if (PosNegSummaryValues.Contains(Datadt.Columns.Count - column.Ordinal))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"PosNegValue\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
if (column.ColumnName.Contains(" Actual"))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else {
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"120px\"},");
}
}
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"align\":\"right\",\"width\":\"70px\"},");
}
}
sbcolModel.Remove(sbcolModel.Length - 1, 1);
sbcolModel.Append("]");
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> drow;
foreach (DataRow dr in Datadt.Rows)
{
drow = new Dictionary<string, object>();
foreach (DataColumn col in Datadt.Columns)
{
drow.Add(GetPivotColumnName(col.ColumnName), dr[col]);
}
rows.Add(drow);
}
StringBuilder sbjsonRows = new StringBuilder();
sbjsonRows.Append(serializer.Serialize(rows));
StringBuilder json = new StringBuilder();
json.Append("{");
json.Append("\"rows\":");
json.Append(sbjsonRows.ToString().Trim());
json.Append("}");
json.ToString();
GridData gridData = new GridData();
gridData.SelectedPractice = practice; // New statement returns practicefilter -- if grid displays this we can remove it
gridData.SelectedLocation = locationFilter;
gridData.SelectedModality = modalityFilter;
gridData.SelectedReferringPractice = referringPractice;
gridData.SelectedPhysicians = referringPhysician;
gridData.SelectedCpt = cpt;
gridData.SelectedSpeciality = speciality;
gridData.PageSize = pageSize;
gridData.RowArea = rowArea;
gridData.IsVolume = isVolume;
gridData.page = 1;
gridData.total = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(ds.Tables[1].Rows[0][0]) / Convert.ToDouble(pageSize)));
gridData.records = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
gridData.col = sbcol.ToString();
gridData.colModel = sbcolModel.ToString();
gridData.rows = sbjsonRows.ToString().Trim();
gridData.order = order;
gridData.orderBy = orderBy;
gridData.direction = direction;
gridData.orderBySummary = orderBySummary;
gridData.orderBySummaryCol = OrderBySummaryCol;
gridData.ShowSubTotalForAllGroup = ShowSubTotalForAllGroup;
//Temporary Solution for getting the practice name for the corresponding practice
//var reader = SqlHelper.ExecuteReader(sqlConnectionString, CommandType.Text, "select practicename from practice where practiceid="+practice);
SqlConnection con = new SqlConnection(sqlConnectionString);
SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = "select practicename from practice where practiceid="+practice;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
returnValue = cmd.ExecuteScalar();
con.Close();
gridData.SelectedPracticeName = returnValue.ToString();
return gridData;
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
When you do
gd = HttpContext.Current.Session["SalesUserSession"] as GridData;
gd is an Object reference to HttpContext.Current.Session["SalesUserSession"]
that's why your session is impacted by your modifications.
this topic may help you achieve what you want :
Deep cloning objects

Search multiple column using multiple control in asp.net using linq

Project_Detail pro = new Project_Detail();
string title=Ttitle.Text;
string year1=Tyear.Text;
string key = Tkeywrds.Text;
string area = Ddl_area.Text;
string categ = Ddl_catgry.Text;
string tech = Ddl_tech.Text;
string type =Ddl_type.Text;
var q = from obj in da.Project_Details
where obj.Project_Title.Contains(title)
|| obj.Submission_Date.Contains(year1)
|| obj.Keywords.Contains(key)
|| obj.Project_Area.Contains(area)
|| obj.Project_Category.Contains(categ)
|| obj.Project_Technology.Contains(tech)
|| obj.Project_Type.Contains(type)
select obj;
if (q != null)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
this code give last record of table and also not give else condition result.
I want result of all condition and want to use LIke satatement.
q is never null. It might be empty, though. So you should change your code to
if (q.Any()) // <<-----
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
You can also use count method .Count()
if (q.count()>0)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}

Enum Ploblem alway value how?

public enum FrameStatus
{
NotReport = 0,
NormalStatus = 1,
NotNormalstatus = 2
}
but alway FrameStatus.NormalStatus how?
public FrameStatus FrameReportStatus(int Framid, string Timebet)
{
foreach (FrameCam fc in al)
{
if (fc.Timebet == Timebet && fc.IdFrame == Framid)
{
if ((int)fc.status == 1) fc.status = FrameStatus.NormalStatus;
else if ((int)fc.status == 2) fc.status = FrameStatus.NotNormalstatus;
else fc.status = FrameStatus.NotReport;
return fc.status;
}
}
return FrameStatus.NotReport;
}
my complete classs
class FrameCam
{
private ArrayList al = new ArrayList();
public string strConnect;
public FrameStatus status = FrameStatus.NormalStatus;
public string Timebet;
public int IdFrame;
public FrameCam()
{
}
public FrameCam(string st, string bt)
{
strConnect = st;
Timebet = bt;
LoadtoList();
}
public FrameStatus GetFramStatus(int Framid, string timebet)
{
foreach (FrameCam fc in al)
{
if (Framid == fc.IdFrame && timebet == fc.Timebet)
{
return fc.status;
}
}
return FrameStatus.NotReport;
}
private void LoadtoList()
{
SqlConnection conn = null;
SqlDataReader sr = null;
try
{
string query =
"SELECT * FROM FrameReport WHERE convert(varchar, GETDATE(), 101) = convert(varchar, DateTimeSign, 101) AND TimeSignBeetWeen='" +this.Timebet+"'";
conn = new SqlConnection(this.strConnect);
conn.Open();
SqlCommand sc = new SqlCommand();
sc.CommandText = query;
sc.Connection = conn;
sr = sc.ExecuteReader();
while (sr.Read())
{
FrameCam fc = new FrameCam();
fc.Timebet = sr["TimeSignBeetWeen"].ToString();
fc.IdFrame = (int)sr["IdFrame"];
if ((int)sr["Status"] == (int)FrameStatus.NormalStatus)
{
status = FrameStatus.NormalStatus;
}
if ((int)sr["Status"] == (int)FrameStatus.NotNormalstatus)
{
status = FrameStatus.NotNormalstatus;
}
else status = FrameStatus.NotReport;
al.Add(fc);
}
}
catch (Exception)
{
}
finally
{
if (sr != null) sr.Close();
if (conn != null) conn.Close();
}
}
public FrameStatus FrameReportStatus(int Framid, string Timebet)
{
foreach (FrameCam fc in al)
{
if (fc.Timebet == Timebet && fc.IdFrame == Framid)
{
if ((int)fc.status == 1) fc.status = FrameStatus.NormalStatus;
else if ((int)fc.status == 2) fc.status = FrameStatus.NotNormalstatus;
else fc.status = FrameStatus.NotReport;
return fc.status;
}
}
return FrameStatus.NotReport;
}
}
You're not assigning anything to fc.Status within LoadToList and the initialize for FrameCam's 'status' field is "FrameStatus.NormalStatus". If you update the code in LoadToList to assign to fc.status (instead of this.status, as is shown here) then it should work as you expect.
As a side note, LoadToList should be a static method, which would have mitigated this problem.
Use a debugger. Step through the code.
The code is not taking the path you think it is taking.
If you do not know how to step through code in a debugger, you MUST learn.
This is not an optional skill for a computer programmer.

Categories