"CS0162: Warning as Error: Unreachable code detected" on Razor View - asp.net-mvc

I have the following code within a script tag on my razor view:
self.regions = [];
#foreach(var region in Model.OperationRegions)
{
<text>
self.regions.push({
regionid: '#region.Region_Id',
regionname: '#region.Title',
selected: ko.observable(#(Model.RegionsList.Contains(region.Region_Id).ToString().ToLower()))
});
</text>
}
self.categories = [];
#foreach(var category in Model.Categories)
{
<text>
self.categories.push({
categoryid: '#category.Category_Id',
title: '#category.Title'
});
</text>
}
For clarity, the code outside of the foreach loops and within the text tags are Javascript and the purpose of the razor code is to populate my Javascript arrays with data from the server.
When I run this I am currently getting a server error saying "CS0162: Warning as Error: Unreachable code detected"
The error is thrown on the second "foreach" in the snippet.
Surprisingly I couldn't find another question referring to this error message on an MVC razor page so I'm posting this here.
My question is why is that line of code considered to be unreachable? I will update this question if I find anything else on my page to be relevant to the issue as I try to debug.

The error has disappeared now. I had renamed a property of my model and not recompiled before trying to load the page again. Recompiling made the error go away. I have no idea how the root cause translated to the error message shown but its fixed now in any case.

This is an extremely poor way to handle this. There's no need to build an array piece by piece like this. Just convert your list to JSON.
self.regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
The only thing this can't handle is making selected an observable. However, you can simply loop through the array and fix this:
for (var i = 0; i < self.regions.length; i++) {
self.regions[i].selected = ko.observable(self.regions[i].selected);
}
However, the better approach is to use another view model:
var OperationRegionViewModel = function (data) {
var self = {};
self.regionid = ko.observable(data.regionid);
self.regionname = ko.observable(data.regionname);
self.selected = ko.observable(data.selected);
return self;
};
Then, you can just do something like:
var regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
self.regions = $.map(regions, new OperationRegionViewModel);
Or, even better build your JSON all at once:
var json = #Html.Raw(Json.Encode(new {
regions = Model.OperationRegions.Select(r => new { ... }),
categories = Model.Categories.Select(c => new { ... }),
// etc
});
Then, inject this all into your view model:
var viewModel = (function (json) {
// other stuff
self.regions = $.map(json.regions, new OperationRegionViewModel);
self.categories = $.map(json.categories, new CategoryViewModel);
// etc
})(json);

Related

How to get the ID of an inserted record in HANA back to SAPUI5 application?

I got an SAPUI5-application in which I create entries and save them via OData-service. That works, the code for the create operation can be found below. What I have to do now is, I need the ID of the inserted record in HANA back in my application. So what I did I implemented a success handler and thought I would get back this ID in the response from my OData-service. But that is not the case, I get back the same value I provided, in this case 0 since this just a dummy value for the OData-service. I did some research on how to tackle this problem, but none of the approaches worked. So I hope someone of you can help me out or got a hint how to do this. Below the code for create-operation, odata-service and the create.xsjs:
Create-operation in SAPUI5:
this.getOwnerComponent().getModel("Mitarbeiter").create("/ARB", oEntry, {
success: function(oData, response){
console.log(response);
}
});
OData-service:
service {
"MITARBEITERABTEILUNG"."ABTEILUNG" as "ABT" navigates ("Mitarbeiter" as "ARB");
"MITARBEITERABTEILUNG"."Mitarbeiter" as "ARB" create using "public.MitarbeiterAbteilung:mitarbeiterMethods.xsjslib::mitarbeiterCreate";
association "Mitarbeiter"
principal "ABT"("ID")
multiplicity "1"
dependent "ARB"("Abteilung")
multiplicity "*";
}
Create.xsjs:
function mitarbeiterCreate(param) {
let aAfterTableName = param.afterTableName;
var oEntry = {};
try {
var statement = param.connection.prepareStatement("SELECT * FROM\"" + aAfterTableName + "\"");
var rs = statement.executeQuery();
var statement2 = param.connection.prepareStatement('SELECT "MITARBEITERABTEILUNG"."MASEQUENCE".NEXTVAL from dummy');
var rs2 = statement2.executeQuery();
while (rs2.next()) {
oEntry.ID = rs2.getInteger(1);
}
statement2.close();
while (rs.next()) {
oEntry.Name = rs.getString(2);
oEntry.Adresse = rs.getString(3);
oEntry.bz = rs.getString(4);
oEntry.Abteilung = rs.getInteger(5);
}
statement = param.connection.prepareStatement('INSERT INTO "MITARBEITERABTEILUNG"."Mitarbeiter" VALUES (?,?,?,?,?)');
statement.setInteger(1, oEntry.ID);
statement.setString(2, oEntry.Name);
statement.setString(3, oEntry.Adresse);
statement.setString(4, oEntry.bz);
statement.setInteger(5, oEntry.Abteilung);
statement.execute();
statement.close();
} catch (e) {
statement.close();
}
}
Answered in the SAP Community here: https://answers.sap.com/questions/566957/how-to-get-the-id-of-an-inserted-record-in-hana-ba.html
The only thing you need to do, is to update the ID value in the "afterTableName" table provided by the function parameter. Something like that:
let statement = param.connection.prepareStatement('update "' + param.afterTableName + '" set ID = ' + oEntry.ID);
statement.executeUpdate();
Of course that needs to be done after you have determined your new ID. In case your column name is not "ID", please replace it with the real column name.

Getting next sibling with class in zepto

Normally this would not be a problem, but this time I don't control the dom. Anyway
<dt>foo</dt>
<dd>bar</dd>
<dd>bar
<div id="myElem">baz</div>
</dd>
<dd>bar</dd>
<dd>bar</dd>
<dd class="moo">bar</dd> <-- I want to get this one
<dd>bar</dd>
<dd>bar</dd>
<dd class="moo">bar</dd>
<dd>bar</dd>
<dd>bar</dd>
Here is what I have tried
$('#myElem').closest('dd').next('.moo').something();
$('#myElem').closest('dd').nextUntil('.moo').something();
However non of these get the next sibling with the class.
Anyone know how to traverse this?
Try
$('#myElem').closest('dd').nextAll('.moo:first').something();
or
$('#myElem').closest('dd').nextUntil('.moo').next().something();
I don't know zepto but from a quick check of the docs it doesn't look like you can do it with a simple chain. Try
var $dd = $('#myElem').closest('dd');
var $moo = $dd.next();
while (!$moo.is('.moo')){
$moo = $moo.next();
if ($moo.length == 0) break;
}
DEMO
You can accomplish by creating a simple new method:
/**
* Get the next element of a particular class, relative to a different element.
*/
var nextOfClass = function(relativeTo, className) {
var el = relativeTo, nextEl;
// Leading period will confuse Zepto.
if (className[0] === '.') className = className.slice(1);
while (el.next()) {
// If target element is found, stop
if (el.hasClass(className)) return el;
nextEl = el.next();
if (nextEl.length === 0) {
// No more siblings. Go up in DOM and restart loop to check parent
el = el.parent();
continue;
}
el = nextEl;
// End of doc. Give up.
if (el.parent().length === 0) return false;
}
};
Then you can simply use the following method:
var moo = nextOfClass($("#myElem"), '.moo');

Previous and current selected options in Prototype

How can I get the previously selected option from a <select> in prototype so I can "rollback" the selection should anything fail in the script ?
You cannot do this directly with prototype, but here is a class to handle "rollbackable" selects:
var UndoableSelect = Class.create({
_$select: null,
_selectedValue : null,
_lastSelectedValue: null,
initialize: function(elementOrId)
{
this._$select = $(elementOrId);
this._lastSelectedIndex = this._$select.selectedIndex;
this._selectedIndex = this._lastSelectedIndex;
this._$select.observe('change', this._changeHandler.bind(this));
},
undoLastSelection: function()
{
this._$select.selectedIndex = this._lastSlectedIndex;
this._selectedIndex = this._lastSelectedIndex;
},
_changeHandler: function(event)
{
this._lastSelectedIndex = this._selectedIndex;
this._selectedIndex = this._$select.selectIndex;
}
});
That you can use like that:
// this one line under has to be called only once per page load (where there is the select of course):
var theSelect = new UndoableSelect('id_of_the_select');
$('id_of_the_select').observe('change', function(event)
{
// your code, if you need to rollback, do this:
theSelect.undoSelection();
});
Sorry not so much explanation but I don't have much time now. I just wrote the code without testing so if any problem let me know and I'll be back on it with more time to fix it ;-)

OData Service not returning complete response

I am reading Sharepoint list data (>20000 entries) using Odata RESTful service as detailed here -http://blogs.msdn.com/b/ericwhite/archive/2010/12/09/getting-started-using-the-odata-rest-api-to-query-a-sharepoint-list.aspx
I am able to read data but I get only the first 1000 records. I also checked that List View Throttling is set to 5000 on sharepoint server. Kindly advise.
Update:
#Turker: Your answer is spot on!! Thank you very much. I was able to get the first 2000 records in first iteration. However, I am getting the same records in each iteration of while loop. My code is as follows-
...initial code...
int skipCount =0;
while (((QueryOperationResponse)query).GetContinuation() != null)
{
//query for the next partial set of customers
query = dc.Execute<CATrackingItem>(
((QueryOperationResponse)query).GetContinuation().NextLinkUri
);
//Add the next set of customers to the full list
caList.AddRange(query.ToList());
var results = from d in caList.Skip(skipCount)
select new
{
Actionable = Actionable,
}; Created = d.Created,
foreach (var res in results)
{
structListColumns.Actionable = res.Actionable;
structListColumns.Created= res.Created;
}
skipCount = caList.Count;
}//Close of while loop
Do you see a <link rel="next"> element at the end of the feed?
For example, if you look at
http://services.odata.org/Northwind/Northwind.svc/Customers/
you will see
<link rel="next" href="http://services.odata.org/Northwind/Northwind.svc/Customers/?$skiptoken='ERNSH'" />
at the end of the feed which means the service is implementing server side paging and you need to send the
http://services.odata.org/Northwind/Northwind.svc/Customers/?$skiptoken='ERNSH'
query to get the next set of results.
I don't see anything particularly wrong with your code. You can try to dump the URLs beign requested (either from the code, or using something like fiddler) to see if the client really sends the same queries (and thus getting same responses).
In any case, here is a sample code which does work (using the sample service):
DataServiceContext ctx = new DataServiceContext(new Uri("http://services.odata.org/Northwind/Northwind.svc"));
QueryOperationResponse<Customer> response = (QueryOperationResponse<Customer>)ctx.CreateQuery<Customer>("Customers").Execute();
do
{
foreach (Customer c in response)
{
Console.WriteLine(c.CustomerID);
}
DataServiceQueryContinuation<Customer> continuation = response.GetContinuation();
if (continuation != null)
{
response = ctx.Execute(continuation);
}
else
{
response = null;
}
} while (response != null);
I had the same problem, and wanted it to be a generic solution.
So I've extended DataServiceContext with a GetAlltems methode.
public static List<T> GetAlltems<T>(this DataServiceContext context)
{
return context.GetAlltems<T>(null);
}
public static List<T> GetAlltems<T>(this DataServiceContext context, IQueryable<T> queryable)
{
List<T> allItems = new List<T>();
DataServiceQueryContinuation<T> token = null;
EntitySetAttribute attr = (EntitySetAttribute)typeof(T).GetCustomAttributes(typeof(EntitySetAttribute), false).First();
// Execute the query for all customers and get the response object.
DataServiceQuery<T> query = null;
if (queryable == null)
{
query = context.CreateQuery<T>(attr.EntitySet);
}
else
{
query = (DataServiceQuery<T>) queryable;
}
QueryOperationResponse<T> response = query.Execute() as QueryOperationResponse<T>;
// With a paged response from the service, use a do...while loop
// to enumerate the results before getting the next link.
do
{
// If nextLink is not null, then there is a new page to load.
if (token != null)
{
// Load the new page from the next link URI.
response = context.Execute<T>(token);
}
allItems.AddRange(response);
}
// Get the next link, and continue while there is a next link.
while ((token = response.GetContinuation()) != null);
return allItems;
}

MARS in SQL Server 2000

I am working in ASP.Net MVC 1.0 and SQL Server 2000 using Entity Framework.
My faulty controller code is given below:
int checkUser = id ?? 0;
string userNameFromNew, userNameToNew;
if (checkUser == 1)
{
userNameFromNew = "U" + Request.Form["usernameFrom"];
userNameToNew = "U" + Request.Form["usernameTo"];
}
else
{
userNameFromNew = "C" + Request.Form["usernameFrom"];
userNameToNew = "C" + Request.Form["usernameTo"];
}
var rMatrix = from Datas in repository.GetTotalRightData()
where Datas.UserName == userNameFromNew.Trim()
select Datas;
Right_Matrix RM = new Right_Matrix();
foreach(var Data in rMatrix)
{
RM.Column_Id = Data.Column_Id;
RM.ProMonSys_Right = Data.ProMonSys_Right;
RM.UserName = userNameToNew;
UpdateModel(RM);
this.repository.AddRightTransfer(RM);
}
return RedirectToAction("RightTransfer");
My faulty model code is given below:
public void AddRightTransfer(Right_Matrix RM)
{
context.AddObject("Right_Matrix", RM);
context.SaveChanges();
}
My code shows error once it is in the model code stating the DataReader is already open and I need to close it first.
Please suggest a workaround.
Try moving the AddRightTransfer loop out of the LINQ foreach, and into a separate one. I think LINQ is executing the first add before the database result set is closed. By moving the call to AddRightTransfer into a second foreach, you should avoid the problem, if that's what is happening.
Here's an example:
List<Right_Matrix> matrixes = new List<Right_Matrix>();
foreach (var Data in rMatrix)
{
Right_Matrix rm = new Right_Matrix();
rm.Column_Id = Data.Column_Id;
rm.ProMonSys_Right = Data.ProMonSys_Right;
rm.UserName = userNameToNew;
UpdateModel(rm);
matrixes.Add(rm);
}
foreach (var rm in matrixes)
{
this.repository.AddRightTransfer(rm);
}
The problem is that you are modifying the database while still iterating over it. Either finish the query before modifying, like this:
foreach(var Data in rMatrix.ToArray())
Or don't modify the database in your loop, like this:
foreach(var Data in rMatrix)
{
RM.Column_Id = Data.Column_Id;
RM.ProMonSys_Right = Data.ProMonSys_Right;
RM.UserName = userNameToNew;
UpdateModel(RM);
context.AddObject("Right_Matrix", RM);
}
context.SaveChanges();
Obviously, those two context. calls would have to be made into methods on your repository, but you get the picture.

Resources