How to append a string to view in mvc3? - asp.net-mvc-3

HI all i have some values...using them i am building a string in my controller i wan to display the string in my view page....
here is my controller code
[ChildActionOnly]
public ActionResult History()
{
//if(Session["DetailsID"]!=null)
//{
int id = Convert.ToInt16(Session["BugID"]);
var History = GetBugHistory(id);
return PartialView(History);
//}
//int id1 = Convert.ToInt16(Session["BugID"]);
//var History1 = GetBugHistory(id1);
//return PartialView(History1);
}
/// <summary>
///To the List of Resolutions and Employeenames Based on BugID
/// </summary>
/// <param>Bug Id</param>
/// <returns>BugHistory</returns>
public List<BugModel> GetBugHistory(int id)
{
var modelList = new List<BugModel>();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("History", conn);
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.Add(new SqlParameter("#BugID", id));
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
StringBuilder sb = new StringBuilder();
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new BugModel();
model.FixedBy = ds.Tables[0].Rows[i]["FixedByEmployee"].ToString();
model.Resolution = ds.Tables[0].Rows[i]["Resolution"].ToString();
model.AssignedTo = ds.Tables[0].Rows[i]["AssignedEmployee"].ToString();
model.Status = ds.Tables[0].Rows[i]["Status"].ToString();
model.ToStatus= ds.Tables[0].Rows[i]["ToStatus"].ToString();
modelList.Add(model);
sb.Append("'" + model.FixedBy + "'" + "has updated the status from" + "'" + model.ToStatus + "'" + "to" + "'" + model.Status + "'" + "and Assigned to" + "'" + model.AssignedTo + "'");
}
return modelList;
}
}
How should i show this string in my partial view page using a foreach loop

anil,
I'd suggest creating a partialview (_BugModelList.cshtml) that handles purely the output display of the BugModel. This may look something like this:
#model IList<BugModel>
<table>
<thead>
<tr>
<th>Fixed by</th>
<th>From Status</th>
<th>To Status</th>
<th>Assigned to</th>
</tr>
</thead>
#{
foreach (var item in Model)
{
<tr>
<td>#item.FixedBy</td>
<td>#item.ToStatus</td>
<td>#item.Status</td>
<td>#item.AssignedTo</td>
</tr>
}
}
</table>
or, if you wanted the single string as per your controller (untested obviously):
#model IList<BugModel>
#{
foreach (var item in Model)
{
<p>
#{ "'" + item.FixedBy + "'"
+ " has updated the status from "
+ "'" + item.ToStatus + "'"
+ " to " + "'" + item.Status + "'"
+ " and Assigned to " + "'" + item.AssignedTo + "'"; }
</p>
}
}
this would then be called from your main view as per the action that you presently have. Obviously, I've formatted it as table but you can refactor that to suit, the logic remains the same.
[Edit] - re-reading your question, you probably want to present the list as a table, rather than as an unordered list. See edit above

Related

Output SQL Table to existing Excel file/ new worksheet in SSIS / C# in script task

Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.

How can Dynamics CRM Statuscodes / Statecode Optionsets sort order be updated?

The UI Editor in Dynamics CRM won't allow system admins to directly edit status/statecode picklists on the Activity Entity. How can the order be edited programatically?
In another question, information is provided about how to get metadata about statuscodes and statecodes:
Dynamics Crm: Get metadata for statuscode/statecode mapping
Microsoft provides a class for sorting order of picklists:
https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327607(v%3dcrm.8)
I have successsfully coded and can retrieve metadata for both standard picklists and for statuscodes picklists (both the statecode and statuscode). I can programatically update the sort order on standard picklists, but when attempting to do so on a statuscode optionset, no errors are thrown and no changes are published to the system.
How can the sort order on the activity statuscode field be updated?
Example code follows, complete with both tests:
namespace ConsoleApps
{
class EditAptStatusCodeOptionSetOrder
{
static void Main()
{
//Connect to Database
string CRMConnectionString = #"AuthType = Office365; URL = https://URLOFSERVER; Username=USERNAME; Password=PASSWORD;";
Console.WriteLine("Connecting to Auric Solar Sandbox Environment Using Ryan Perry's Credentials. ");
CrmServiceClient crmServiceClient = new CrmServiceClient(CRMConnectionString);
IOrganizationService crmService = crmServiceClient.OrganizationServiceProxy;
//Test Retrieving Stage (Statuscode) from Test Entity.
//Get the Attribute
RetrieveAttributeRequest retrieveStatusCodeAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveStatusCodeAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveStatusCodeAttributeRequest);
Console.WriteLine("Retreived Attribute:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.LogicalName);
Console.WriteLine("Retreived Attribute Description:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.Description);
StatusAttributeMetadata statusCodeMetaData =
(StatusAttributeMetadata)retrieveStatusCodeAttributeResponse.AttributeMetadata;
Console.WriteLine("Metadata Description:" +
statusCodeMetaData.Description);
Console.WriteLine("Metadata IsValidForUpdate:" +
statusCodeMetaData.IsValidForUpdate.ToString());
Console.WriteLine("OptionSet Type:" +
statusCodeMetaData.OptionSet.Name.ToString());
Console.WriteLine("OptionSet Name:" +
statusCodeMetaData.OptionSet.OptionSetType.ToString());
Console.WriteLine("Retrieved Options:");
foreach (OptionMetadata optionMeta in statusCodeMetaData.OptionSet.Options)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] optionList = statusCodeMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Option Array:");
foreach (OptionMetadata optionMeta in optionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedOptionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderStatusCodeOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "statuscode",
EntityLogicalName = "new_testentity",
Values = sortedOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderStatusCodeOptionRequest Created.");
//Execute Request. //////THIS DOESN'T THROW ERRORS, BUT DOESN'T UPDATE SYSTEM.
OrderOptionResponse orderStatusCodeResponse = (OrderOptionResponse)crmService.Execute(orderStatusCodeOptionRequest);
Console.WriteLine("Request Executed");
////////////////////////////////////////PICKLIST TEST//////////////////////////////////
Console.WriteLine("\n\nTestingPickList");
RetrieveAttributeRequest retrieveTestPicklistAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "new_testpicklist",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveTestPicklistAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveTestPicklistAttributeRequest);
PicklistAttributeMetadata pickListMetaData =
(PicklistAttributeMetadata)retrieveTestPicklistAttributeResponse.AttributeMetadata;
Console.WriteLine("Retrieved Picklist Options:");
foreach (OptionMetadata optionMeta in pickListMetaData.OptionSet.Options)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] picklistOptionList = pickListMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Picklist Option Array:");
foreach (OptionMetadata optionMeta in picklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedPicklistOptionList = picklistOptionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Picklist Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedPicklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderPicklistOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "new_testpicklist",
EntityLogicalName = "new_testentity",
Values = sortedPicklistOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderPicklistOptionRequest Created.");
//Execute Request.
OrderOptionResponse orderPicklistResponse = (OrderOptionResponse)crmService.Execute(orderPicklistOptionRequest);
Console.WriteLine("Order Picklist Request Executed");
//Publish All.
Console.WriteLine("Publishing. Please Wait...");
PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
crmService.Execute(publishRequest);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}

whats failed due to data type mismatch in criteria expression c#?

am trying to develop a c# standalone application and my insert code has no error but when i click it will insert to first table or crtPro perfectly but it didn't add to the second table , can anyone give me some hint...???
here is my code for insert code...
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Documents and Settings\abel\My Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Address = txtAddress.Text.ToString();
//String Wereda = txtWereda.Text.ToString();
//String Kebele = txtKebele.Text.ToString();
//String House_No = txtHouse.Text.ToString();
//String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
//String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String Status = ToString();
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "INSERT INTO crtPro(Name,Address,Email,Tel,Item,Dep,Status,Remark)VALUES('" + Name + "','" + Address + "','" + Email + "','" + Tel + "','" + Item + "','" + Dep + "','" + Remark + "')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
String my_querry1 = "SELECT LAST(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
//txtStatus.Text = var;
String PID = ToString();
String my_querry2 = "INSERT INTO crtItemLicense(PID,Type,Brand,License_No,Date_issued)VALUES('" +PID + "','" + Type + "','" + Brand + "','" + License_No + "','" + Date_issued + "')";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
There are a couple of calls like:
String PID = ToString();
That will try to get a string representation of 'this', which is your form. That is probably not what you want to be inserting into the database. You probably meant
String PID = var.ToString();
If that isn't it, then try putting more tracewrites (or using a debugger) to narrow the problem down to find which one of your sql statements is causing the problem.
Also once you have it working, try entering this in the name field of your form:
Robert"); DROP TABLE crtPro;--
and then do some googling about SQL injection (apologies to XKCD).

Is there any way to replace Response.Write?

My problem is, I have the following function:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
.....
}
Session["Tarif"] - contains multidimensional array List and when I'm loading my page it's giving this Error that
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
When I delete <% Response.Write(Session["Tarif"]); %> it doesn't give this error. So, how can I replace this code to get array List from Session["Tarif"] without using the code blocks <% %>?
This is my Array List code in C#:
public void getTarifList()
{
int intRows = 0;
string strTarif = "null";
Session["Tarif"] = "null";
SqlCommand cmdTarif = new SqlCommand("sp_SIMPay_GetTarifList");
cmdTarif.CommandType = CommandType.StoredProcedure;
DataTable dtTarif = SQL.GetData(cmdTarif);
if (dtTarif.Rows.Count > 0)
{
intRows = dtTarif.Rows.Count;
strTarif = "new Array(" + intRows + ");";
int intIndex = 0;
foreach (DataRow dRows in dtTarif.Rows)
{
strTarif += "arrTarif[" + intIndex + "] = new Array('" + dRows["TarifName"] + "', '" + dRows["ProviderID"] + "', '" + dRows["CodeID"] + "');";
intIndex++;
}
}
else
{
strTarif = "null";
}
Session["Tarif"] = strTarif;
}
My full script:
function change_tarif(param) {
var arrTarif = <% Response.Write(Session["Tarif"]); %>
var select = document.getElementById('TarifList');
var i = 0;
if (arrTarif != null) {
for (i = 0; i < arrTarif.length; i++) {
if (arrTarif[i][1] == '98' && param == '98') {
clear_tarif();
select.options[select.options.length] = new Option('' + arrTarif[i][0] + '', '' + arrTarif[i][2] + '');
break;
}
else {
clear_tarif();
select.options[select.options.length] = new Option('Default Tarif', '');
}
}
}
}
This happens because somewhere in your page code you do something like (just an example - it doesn't matter that it's a Label here, any dynamically added/removed control would trigger the error):
Label lbl = new Label ();
lbl.Xxxx = ...;
Controls.Add ( lbl ); // this is what triggers your issue
When you have <%= ... %> in the same container where you also try to dynamically add controls through the use of the Controls collection of that container (Page, Panel, etc.), you'll get that error that you saw.
If you can, try to remove the code that dynamically adds/removes the control to the container (the same container where you have the <%= ... %> and then your <%= ... %> block will start working.
To remove the dynamic logic that adds/removes control(s), simply put those controls into the container like any other control, like
<asp:Label runat="server" id="lbl" ... />
and then simply show/hide the control when you need it. This way the control is always present in the page, you won't have to add/remove it during run-time and then you can have code blocks in the same container.
Here's a quick example that would create this error:
...
<div runat="server" id="div1">
<asp:Label runat="server" id="lbl1" /><br />
<span>Name: <%= Session["name"] %></span>
</div>
...
// in code-behind
protected override void OnLoad ( EventArgs e )
{
Label lbl2 = new Label ();
lbl2.Text = "Time: " + DateTime.Now.ToString ();
// Error: you cannot modify the Controls collection if
// the same control contains code blocks
div1.Controls.Add ( lbl2 );
}
You can use Expression (Equivalent to Response.Write()).
function change_tarif(param) {
var arrTarif = <%= Session["Tarif"] %>;
}
EDIT : I've customized your code,
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
getTarifList();
}
public void getTarifList()
{
Session["Tarif"] = "null";
StringBuilder sb = new StringBuilder();
sb.AppendLine("new Array(" + 3 + ");");
for(int i=0;i<3;i++)
{
sb.AppendLine("arrTarif[" + i + "] = new Array('A" + i + "', 'B" + i + "', 'C" + i + "');");
}
Session["Tarif"] = sb.ToString();
}
And markup,
<script type="text/javascript">
function change_tarif(param){
var arrTarif = <% Response.Write(Session["Tarif"]); %>
return arrTarif;
}
console.log(change_tarif('test'));
</script>

How to replace a String at the end when Building a String with multiple Data?

HI all i am Building A string Which looks like this
[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
i am building this string with this data
public JsonResult ResourceBugReports()
{
int projectid;
int Releasphaseid;
projectid = 16;
Releasphaseid = 1;
var ResourceReports = db.ExecuteStoreQuery<ResourceModel>("ResourceBugReports #ProjectId,#ReleasePhaseId", new SqlParameter("#ProjectId", projectid), new SqlParameter("#ReleasePhaseId", Releasphaseid)).ToList();
DataSet ds = new DataSet();
var model1 = new WeeklyBugCount
{
Resources = ResourceReports
};
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
foreach (var row in model1.Resources)
{
BugsCount = BugsCount + row.Assignedbugs + ",";
}
foreach (var row in model1.Resources)
{
BugsCount1 = BugsCount1+ row.Closedbugs + ",";
}
foreach (var row in model1.Resources)
{
Bugscount2 = Bugscount2 + row.Fixedbugs + "," ;
}
foreach (var row in model1.Resources)
{
BugsCount3 = BugsCount3 + row.Reopenedbugs + ",";
}
ComboinedString = ResourceName1 + "/" + BugsCount + "/" + BugsCount1 + "/" + Bugscount2 + "/" + BugsCount3;
return Json(ComboinedString, JsonRequestBehavior.AllowGet);
}
my
ComboinedString =[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
but i want this string
ComboinedString =[Anil Kumar K,Niharika,Raghu/4,0,0/3,0,0,/1,1,1/1,0,0]
i want to remove this "," before the "/" in this strin or replace it..can any one help me
Add this statement
I hope it will help you
String CombinedString1 = CombinedString.Replace(",/", "/");
A simple solution is a search and replace on the string replacing ",/" with "/".
A better solution is, rather than using a for() loop and appending a comma at the end of each value, is use String.Join(). For example, replace:
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
with
ResourceName1 = string.Join(",", model1.Resources.ToArray())
This will remove the trailing comma.
A simple solution would be to use String.EndsWith() function i.e.
string str = "ksjf,sjsfj,sfs,";
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}
Off the top of my head, you could try to replace with a simple regular expression:
string input = "dsgd,sdgsdg,dsgsdg,sdg,";
string output = Regex.Replace(input, ",$", "");
//output: "dsgd,sdgsdg,dsgsdg,sdg"
#user1542652's solution is simple and works just as well.

Resources