Html strip in asp.net - asp.net

I have used a ckeditor in which user can submit data to the database in styles but when the data is populated in the datagrid then also it comes with same styles in IE
but I want it to be in plain text when get populated.
the function for populating the data is as follows:
protected void LoadQA(int intQuestionId)
{
string strSelectQuery = "SELECT TITLE, DESCRIPTION, ANSWER, FK_OWNER_ID, CREATED_ON FROM M_QA WHERE PK_ID = "
+ intQuestionId + " AND IS_ACTIVE = 1";
OleDbConnection connectionSelectQuestion = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand commandSelectQuestion = new OleDbCommand(strSelectQuery, connectionSelectQuestion);
OleDbDataReader readerSelectQuestion;
try
{
connectionSelectQuestion.Open();
readerSelectQuestion = commandSelectQuestion.ExecuteReader();
if (readerSelectQuestion.Read())
{
lblHeader.Text = "View Q&A";
txtTitle.Text = readerSelectQuestion["TITLE"].ToString();
if (readerSelectQuestion["TITLE"].ToString().Length > 50)
{
ViewState["QA_Title"] = readerSelectQuestion["TITLE"].ToString().Substring(0, 50) + "...";
}
else
{
ViewState["QA_Title"] = readerSelectQuestion["TITLE"].ToString();
}
txtDescription.Text = readerSelectQuestion["DESCRIPTION"].ToString();
hlnkQuestionBy.Text = clsCommons.SayUserName(readerSelectQuestion["FK_OWNER_ID"].ToString());
hlnkQuestionBy.NavigateUrl = "AddMember.aspx?id=" + readerSelectQuestion["FK_OWNER_ID"].ToString();
lblAskedOn.Text = readerSelectQuestion["CREATED_ON"].ToString();
if (this.Session["UserId"].ToString() != "1")
{
btnUpdate.Visible = false;
txtEditorAnswer.Visible = false;
divQaDescription.Visible = true;
divQaDescription.InnerHtml = Server.HtmlDecode(readerSelectQuestion["ANSWER"].ToString());
}
else
{
txtEditorAnswer.Text = readerSelectQuestion["ANSWER"].ToString();
}
}
else
{
lblError.Text = "ERROR WHILE READING QA DATA!";
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
lblError.Text = ex.Message;
}
finally
{
if (connectionSelectQuestion != null)
{
connectionSelectQuestion.Close();
}
}
}
What changes I need to make to get the plain text in the datagrid.
Thanks for ur help..

here is some sql code that can strip the tags for you.
declare #string varchar(max), --string to remove html from
#a varchar(max), --holds left part of string after removal
#b varchar(max) --holds right part of string after removal
set #string='<htlml><head><title></title></head><body>This is the body. <p>This is a paragraph.</p></body></html>'
declare #i bit, --determines if there are any more tags in the string
#start int, --position of the first < character
#end int --position of the first > character
set #i='false' --set default value
--set the positions of the first tag
select #start=CHARINDEX('<',#string),
#end=charindex('>',#string)
--only do the loop if there is a tag
if (#start>0 and #end>0) set #i='true'
while (#i='true')
begin
set #a='' --reset
set #b='' --reset
set #a=LEFT(#string,#start-1)
set #b=RIGHT(#string,len(#string)-#end)
--select #a, #b
set #string=#a+#b
select #start=CHARINDEX('<',#string),
#end=charindex('>',#string)
if (#start>0 and #end>0) set #i='true' else set #i='false'
end
select #string
keep in mind, however, that this code does not take into consideration if the text contains a < or >.

Related

Pulling data from Sqlite cursor loader

OK I have a app that has a Listview and uses sqlite data to populate it. But I also want to be able to email the contents of each view for the body of the message. I tried doing this with a global string variable and catching the data in the CarCursorAdapter activity in the BindView section like this:
// Update the TextViews with the attributes for the current move
vinTxtView.setText(vinStr);
dateTxtView.setText(dateStr);
mvFromTxtView.setText(mvFrom);
mvToTxtView.setText(mvTo);
MyProperties.getInstance().bodyStrGlobal = MyProperties.getInstance().bodyStrGlobal+vinStr+"-"+mvFrom+"->"+mvTo+"-"+dateStr+"\n";
And then I use that string in the email intent. But the problem is it keeps adding to this string every time the listview is populated so I get all kinds of double entries. What would be the best way to just capture this once when the email feature is selected? Or reset the string to null at some place? Maybe just read from each listview item instead of from the cursor loader? There is probably a way to just cycle through the database table but I'm getting all kinds of errors and haven't had any luck.
Found this to work. My MainActivity is very busy now, but everything works.
public String getEmailText(){
String tempStr = "";
String[] projection = {
CarEntry._ID,
CarEntry.COLUMN_CAR_VIN,
CarEntry.COLUMN_CAR_DATE,
CarEntry.COLUMN_CAR_MOVEFROM,
CarEntry.COLUMN_CAR_MOVETO};
Cursor cursor = getContentResolver().query(Uri.parse("content://gregorykraft.com.scanvin/cars"),projection,null,null,null);
if
(cursor == null || cursor.getCount() < 1) {
Toast.makeText(this, getString(R.string.error_uri),
Toast.LENGTH_SHORT).show();
return "";
}
int i = 0;
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
i++;
String s =String.valueOf(i);
String vinStr = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_VIN));
String mvFrom = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_MOVEFROM));
String mvTo = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_MOVETO));
String dateStr = cursor.getString(cursor.getColumnIndex(CarEntry.COLUMN_CAR_DATE));
tempStr = tempStr+s+") "+vinStr + "-" + mvFrom + "->" + mvTo + "-" + dateStr + "\n";
cursor.moveToNext();
}
cursor.close();
}
return tempStr;
}

Trying to understand sorting in the Table widget for a Page

I am trying to understand how sorting works in Table widgets works when loading a page. For most of my pages using the Table widget, the page loads sorted by the first column.
I do see the below code in the onAttach event for the Table panel in a page. I am wondering if this is the code that sets the sorting when a page loads.
// GENERATED CODE: modify at your own risk
window._am = window._am || {};
if (!window._am.TableState) {
window._am.TableState = {};
window._am.inFlight = false;
}
if (!window._am.sortTableBy) {
window._am.sortTableBy = function(datasource, field, fieldHeader, tableState) {
if (!field) {
throw "Can't sort the table because specified field was not found.";
}
tableState.inFlight = true;
if (tableState.sortByField === field.name) {
tableState.ascending = !tableState.ascending;
} else {
if (tableState.fieldHeader) {
tableState.fieldHeader.text = tableState.fieldHeaderText;
tableState.fieldHeader.ariaLabel = "";
}
tableState.sortByField = field.name;
tableState.ascending = true;
tableState.fieldHeader = fieldHeader;
tableState.fieldHeaderText = fieldHeader.text;
}
datasource.query.clearSorting();
var sortDirection = tableState.ascending ? "ascending" : "descending";
datasource.query.sorting[field.name]["_" + sortDirection]();
datasource.query.pageIndex = 1;
datasource.load(function() {
tableState.inFlight = false;
fieldHeader.text = fieldHeader.text.replace(/ (\u25B2|\u25BC)/g, "");
if (tableState.sortByField === field.name) {
fieldHeader.ariaLabel = fieldHeader.text + " sort " + sortDirection;
fieldHeader.text = fieldHeader.text + (tableState.ascending ? " \u25B2" : " \u25BC");
app.accessibility.announce(fieldHeader.ariaLabel);
}
});
};
}
Sorting is set on your datasource.
Click the model (top left) that your table is using.
Click Datasources and expand your Datasource (there will only be one, unless you have created additional ones).
Once you choose the field you want the table to use for sorting, you can choose "Ascending" or "Descending".
The problem is with adding new records from a separate create form. The new records always appear at the end of the list , until a subsequent 'load' is performed.

How to select multiple lines using java Selenium automation testing?

I tried to select multiple lines using selenium automation like below.
this.selectLineInTable(Locator.LOCATOR_LIST, "name", t1.getName()).
this.selectLineInTable(Locator.LOCATOR_LIST,"name",t2.getName()));
but its not working. Can anyone help me how to solve this issue?
try something like below:
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.xpath("first element to select"))).click().build().perform();
act.moveToElement(driver.findElement(By.xpath("second element to select"))).click().release().build().perform();
Actions act = new Actions(driver);
String m1 = this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psv.getName());//1st element
String m2=this.selectLineInTable(Constant.LOCATOR_LIST_MOFULL, "name",psTest.getName());// 2nd element
act.keyDown(Keys.CONTROL).moveToElement(driver.findElement(By.name(m1))).click().build().perform();
act.moveToElement(driver.findElement(By.name(m2))).click().release().build().perform();
protected String selectLineInTable(String scLocatorBody, String key, String value) throws Exception {
String scLocatorLine = this.findLineInTable(scLocatorBody, key, value);
if (scLocatorLine == null) {
// No line for key / value
this.logError("The row [" + key + "=" + value + "] does not exist", null);
} else {
// Click on the line
StringBuffer lRow = new StringBuffer();
lRow.append(scLocatorLine).append("col[fieldName=").append(key).append("]/");
this.clickOnElement(lRow.toString());
sleep(500);
}
return scLocatorLine;
}
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"scLocator=//ListGrid[ID=\"ssr_grid\"]/body/row[0]/"}

Allowing the attacker to access unathorized records finding

I have a scan finding and hope someone can provide any ideas as to best ways to resolve the issue. First I will show the scan Finding then my code and finally what the scanner's recommended solution is.
Finding
Without proper access control, the method GetAttributeKey() in Provider.cs can execute a SQL statement on line 163 that contains an attacker-controlled primary key, thereby allowing the attacker to access unauthorized records.
Rather than relying on the presentation layer to restrict values submitted by the user, access control should be handled by the application and database layers. Under no circumstances should a user be allowed to retrieve or modify a row in the database without the appropriate permissions. Every query that accesses the database should enforce this policy, which can often be accomplished by simply including the current authenticated username as part of the query.
My Code:
Offending line:
myParam.SqlParam.Value = attribute;
Method:
public string GetAttributeKey(string attribute)
{
string qry = "SELECT ws_attribute_key FROM webservice_attributes WHERE ws_attribute = #attribute";
QueryContainer Instance = new QueryContainer(qry);
MyParam myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#attribute", Instance.AddParameterType(_DbTypes._string));
myParam.SqlParam.Value = attribute;
Instance.parameterList.Add(myParam);
object key = ExecuteScaler(Instance);
return Convert.ToString(key);
}
Scanner's Recommend fix:
string user = ctx.getAuthenticatedUserName();
int16 id = System.Convert.ToInt16(invoiceID.Text);
SqlCommand query = new SqlCommand(
"SELECT * FROM invoices WHERE id = #id AND user = #user", conn);
query.Parameters.AddWithValue("#id", id);
query.Parameters.AddWithValue("#user", user);
SqlDataReader objReader = query.ExecuteReader();
I think the problem is dealing with the code calling the GetAttributeKey. The method is called only if the user has no access to to the Attribute. I think I need some type of checking. Here is the calling code:
if (result.Rows.Count > 0)
{
// get the attribute
DataRow[] rows = result.Select("ws_attribute = '" + attribute + "'");
if (rows.Length > 0)
{
// check time range
string hr = DateTime.Now.Hour.ToString();
DataRow[] valid = result.Select("ws_attribute = '" + attribute + "' AND start_time <= " + hr + " AND end_time >= " + hr);
if (valid.Length > 0)
{
ws_user_attribute_key = Convert.ToInt32(valid[0]["ws_user_attribute_key"].ToString());
ret = true;
// generate salt
TextEncryptor te = new TextEncryptor();
salt = te.CreateSalt(8);
// save to the log, return false if failed to log
if (!LogTransfer(ipAddress, accessDate, fileName, ws_user_attribute_key, salt, out logKey))
return false;
}
else
{
ret = false;
LogInvalidAccess(username, rows[0]["ws_attribute_key"].ToString(), ipAddress, accessDate, WSInvalidAccessReason.OutsideValidTimeRange);
}
}
else
{
// if user has no access to attribute
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.AttributeNotAccessible);
}
}
else
{
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.InvalidAccount);
}

How to check for a specific value in List<T> foreach loop

Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.
For example how do I…
If (value.something_2 == "Null")
{
value.something_2 == ".";
}
Elseif (value.something_2 == " ")
{
value.something_2 == "0";
}
How would I incorporate the above example within the “foreach” loop?
See code below.
protected void MyReport(string filename, IMyRepository repository)
{
using (FileStream fileStream = new FileStream(Server.MapPath(#"~/Includes/") + filename, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
List<Report> _report = repository.GetMyReport().ToList();
foreach (var value in _report)
{
String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_1,
values.something_2,
value.something_3);
String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_4,
values.something_5,
value.something_6);
Writer.WriteLine(row01);
Writer.WriteLine(row02);
}
}
writer.Close();
}
}
There is no clever built-in String.Format that you can do for this if that's what you have in mind. However, the compiler has some tricks that can reduce the amount of code you need to write e.g.
// if it's null, assign it to "."
var s2 = value.something_2 ?? ".";
// it can never be null here, so if there is whitespace default to "0"
value.something_2 = String.IsNullOrWhitespace(s2) ? "0" : s2;
If I'm understanding what you're saying, it might be easier just to have another function returning the (possibly) modified string and just pass each of your values into it, inline.
Sting row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", myFunc(value.somthing_1), myFunc(values.something_2), myFunc(value.something_3));
and then have this in the same class
private string myFunc(string something){
if (something == “Null”){
return “.“;
} else if (something == “ “) {
return “0”;
} else {
return something;
}
}

Resources