How to do string concatenate inside viewmodel observe? - android-studio

So the Categories here is a List<Category> which has id and name attribute. I want to concat all of category.name elements in the list before I bind it to view. But the categoryString still "".
private fun getData(id: Int){
buyerViewModel.getProductDetail(id).observe(viewLifecycleOwner){
it.data.let { data ->
var categoryString = ""
data?.Categories?.forEachIndexed { index, category ->
if(index == data?.Categories.size - 1){
categoryString.plus(category.name)
} else {
categoryString.plus(category.name + ", ")
}
}
binding.apply {
Glide.with(requireContext()).load(data?.image_url).into(vpImage)
tvItemNama.text = data?.name
tvItemCategory.text = categoryString
tvItemHarga.text = data?.base_price!!.toRp()
tvDeskripsi.text = data.description
}
}
}
}

Related

Changing the Default Option for Column Filters

Is it possible to change the default option all column filters? I'm pretty sure I can accomplish this with some JavaScript, but I'd like to know if there's any way within the Acumatica framework to change this.
The answer will be no. The filter is inside the PX.Web.UI.dll in the PXGridFilter class which is an internal class. The property that you are interested in is the Condition.
The value is set inside one of the private methods of the PXGrid class. The code of the method is below:
private IEnumerable<PXGridFilter> ab()
{
List<PXGridFilter> list = new List<PXGridFilter>();
if (this.FilterID != null)
{
Guid? filterID = this.FilterID;
Guid guid = PXGrid.k;
if (filterID == null || (filterID != null && filterID.GetValueOrDefault() != guid))
{
using (IEnumerator<PXResult<FilterRow>> enumerator = PXSelectBase<FilterRow, PXSelect<FilterRow, Where<FilterRow.filterID, Equal<Required<FilterRow.filterID>>, And<FilterRow.isUsed, Equal<True>>>>.Config>.Select(this.DataGraph, new object[]
{
this.FilterID.Value
}).GetEnumerator())
{
while (enumerator.MoveNext())
{
FilterRow row = enumerator.Current;
string dataField = row.DataField;
PXCache pxcache = PXFilterDetailView.TargetCache(this.DataGraph, new Guid?(this.FilterID.Value), ref dataField);
if (this.Columns[row.DataField] != null)
{
List<PXGridFilter> list2 = list;
int valueOrDefault = row.OpenBrackets.GetValueOrDefault();
string dataField2 = row.DataField;
string dataField3 = row.DataField;
int value = (int)row.Condition.Value;
object value2 = pxcache.ValueFromString(dataField, row.ValueSt);
string valueText = row.ValueSt.With((string _) => this.Columns[row.DataField].FormatValue(_));
object value3 = pxcache.ValueFromString(dataField, row.ValueSt2);
string value2Text = row.ValueSt2.With((string _) => this.Columns[row.DataField].FormatValue(_));
int valueOrDefault2 = row.CloseBrackets.GetValueOrDefault();
int? #operator = row.Operator;
int num = 1;
list2.Add(new PXGridFilter(valueOrDefault, dataField2, dataField3, value, value2, valueText, value3, value2Text, valueOrDefault2, #operator.GetValueOrDefault() == num & #operator != null));
}
}
return list;
}
}
}
if (this.FilterRows != null && this.FilterRows.Count > 0)
{
for (int i = 0; i < this.FilterRows.Count; i++)
{
PXFilterRow row = this.FilterRows[i];
list.Add(new PXGridFilter(row.OpenBrackets, row.DataField, row.DataField, (int)row.Condition, row.Value, row.Value.With(delegate(object _)
{
if (this.Columns[row.DataField] == null)
{
return _.ToString();
}
return this.Columns[row.DataField].FormatValue(_);
}), row.Value2, row.Value2.With(delegate(object _)
{
if (this.Columns[row.DataField] == null)
{
return _.ToString();
}
return this.Columns[row.DataField].FormatValue(_);
}), row.CloseBrackets, row.OrOperator));
}
}
return list;
}
UPDATE
The below JS code allows you to change the condition of the last set filter:
px_all.ctl00_phG_grid_fd.show();
px_all.ctl00_phG_grid_fd_cond.items.items[7].setChecked(true);
px_all.ctl00_phG_grid_fd_ok.element.click();
px_all.ctl00_phG_grid_fd_cond.items.items[7].value "EQ"
px_all.ctl00_phG_grid_fd_cond.items.items[8].value "NE"
px_all.ctl00_phG_grid_fd_cond.items.items[9].value "GT"
px_all.ctl00_phG_grid_fd_cond.items.items[13].value "LIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[14].value "LLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[15].value "RLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[16].value "NOTLIKE"
px_all.ctl00_phG_grid_fd_cond.items.items[18].value "ISNULL"
px_all.ctl00_phG_grid_fd_cond.items.items[19].value "ISNOTNULL"

Custom validation are not executing on focus change of applied control but works well in case of form submit

I am using normal mvc textboxfor on strong view, I have created custom validation attribute (the detailed code explained below).
On form submit everything works fine. In case if validation fails by natural it shows error message as configured.
Now when I enter the correct value inside text box I expect the error message to be vanished automatically but this does not happen until I post the form
JS File
$.validator.addMethod('validaterequiredif', function (value, element, parameters) {
var id = parameters['dependentproperty'];
var clickValue = $("input[name=" + id + "]:checked").val();
// get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
if (clickValue == targetvalue) {
if (value == null) {
return false;
}
else {
return $.validator.methods.required.call(
this, value, element, parameters);
}
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.add(
'validaterequiredif',
['dependentproperty', 'targetvalue'],
function (options) {
options.rules['validaterequiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['validaterequiredif'] = options.message;
});
Server side custom validator class as below
public class ValidateRequiredIf : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public ValidateRequiredIf(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
//if (!_innerAttribute.IsValid(value))
if (value == null)
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "validaterequiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
}
Model property
[ValidateRequiredIf("IsFeederSelected", "True", ErrorMessage = "Please select atleast one feeder")]
public List<string> selectedMeterName { get; set; }
Strongly typed view
<div class="meterTextboxRadio col-md-4">
<p>
#Html.RadioButtonFor(m => m.IsFeederSelected, true, new { #class = "radio", #Name = "IsFeederSelected", value = "meter", id = "rdbMeterConsumption", #checked = "checked" })
<span> Feeder</span>
#Html.RadioButtonFor(m => m.IsFeederSelected, false, new { #class = "radio", #Name = "IsFeederSelected", value = "group", id = "rdbGroupConsumption",style= "margin-left: 30px;" })
<span> Group</span>
</p>
<div class="group dropdownhidden" id="MeterNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedMeterName, Model.MeterName
, new { #class = "chosen-select" ,#id= "ddlConsumptionMeterName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Feeders.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
<div class="group dropdownhidden" id="GroupNameConsumption" style="margin-top:4px;">
#Html.DropDownListFor(m => m.selectedGroupName, Model.GroupName
, new { #class = "chosen-select", #id = "ddlConsumptionGroupName", multiple = "multiple", Style = "width:100%", data_placeholder = "Choose Group.." })
<span class="highlight"></span> <span class="bar"></span>
</div>
#Html.ValidationMessageFor(m => m.selectedMeterName, "", new { #class = "error" })
#Html.ValidationMessageFor(m => m.selectedGroupName, "", new { #class = "error" })
</div>
Please provide some inputs for the same
Thanks.

C# - How To Check Object Type Using If Statement

i'm currently writing an application with a parent class named 'Vehicle' and two children classes named 'Car' and 'Truck'. My problem is that I would like to search through the full list of Vehicles and return only each car, or each truck depending on what object is placed into a method. Right now I have had to write a method for ach search term such as below:
public string searchCarsByName(string nameString)
{
string carNames = "";
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
carNames += car.ToString();
}
}
if (carNames == "")
{
return "No cars found";
}
else
{
return carNames;
}
}
public string searchTrucksByName(string nameString)
{
string truckNames = "";
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
truckNames += name.ToString();
}
}
if (truckNames == "")
{
return "No vehicle found";
}
else
{
return truckNames;
}
}
My only problem is that the names isn't the only way I would like to search, so for each search I am going to perform then I will have to write two methods. What i'm looking for is a way to pass in an Object to the method, and then dependent on the object it will append the necessary details to the string such as below:
public string searchVehiclesByName(Vehicle nameString)
{
string vehicleNames = "";
if(Vehicle.Type == car)
{
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
vehicleNames += car.ToString();
}
}
}
else
{
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
vehicleNames += truck.ToString();
}
}
}
if (vehicleNames == "")
{
return "No vehicles found";
}
else
{
return vehicleNames;
}
}
}
Essentially what I need is a way to pass in a parent object and check if an object is of a certain child type before creating the resultant string, rather than having to pass each individual type of child object into a method to get the results I want.
Thank you in advance.
Please have a look at this: Type Checking: typeof, GetType, or is?
public string searchVehiclesByName(Vehicle vehicle)
{
string vehicleNames = "";
if(vehicle.GetType() == typeof(Car))
{
foreach (Car car in Vehicles.OfType<Car>())
{
if (car.Name.Contains(nameString))
{
vehicleNames += car.ToString();
}
}
}
else
{
foreach (Truck truck in Vehicles.OfType<Truck>())
{
if (truck.Name.Contains(nameString))
{
vehicleNames += truck.ToString();
}
}
}
if (vehicleNames == "")
{
return "No vehicles found";
}
else
{
return vehicleNames;
}
}
Hope this helps.

Filter a SharePoint list by audience

I am very new to Sharepoint development. I have the following code that I need to have display the list items by targeted audience. I know I am suppose to add something like this
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in list.Items)
{
// get roles the list item is targeted to
string audienceFieldValue = (string)listItem[k_AudienceColumn];
// quickly check if the user belongs to any of those roles
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader,
audienceFieldValue,
false))
But I have no idea where to place it in my code below. Please I would appreciate any of your advise.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
namespace PersonalAnnouncements.PersonalAnnouncements
{
[ToolboxItem(false)]
public class PersonalAnnouncements : Microsoft.SharePoint.WebPartPages.WebPart
{
// Fields
private string _exceptions = "";
private AddInsEnum DE = AddInsEnum.HyperLink;
private const AddInsEnum DefaultAddInsEnum = AddInsEnum.HyperLink;
private const TheDateFormat DefaultDateFormat = TheDateFormat.MonthDayYear;
private const PeriodEnum DefaultPeriod = PeriodEnum.Five;
private const string defaultText = "Your text here";
private const string DefaultURL = "DispForm.aspx";
private TheDateFormat DF = TheDateFormat.MonthDayYear;
private string endField = "Image URL";
private const string imgTURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private const string imgURL = "/_layouts/NewsViewer/banner1.jpg";
protected Label lblError;
private const string listText = "";
private string listViewFields = "";
private PeriodEnum Period = PeriodEnum.Five;
private string sImageURL = "/_layouts/NewsViewer/banner1.jpg";
private string siteURLtext = "Your Site here";
private string startField = "Body";
private string sTImageURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private string sTimeField = "/_layouts/NewsViewer/style_smaller.css";
private string sYAxisTitle = "15";
private string text = "Your text here";
private string ThumbImageField = "";
private const string timer = "/_layouts/NewsViewer/style_smaller.css";
private string titleField = "";
private string urltocalendar = "DispForm.aspx";
private const string yaxistit = "15";
// Methods
protected override void CreateChildControls()
{
HtmlTable table;
HtmlTableRow row;
HtmlTableCell cell;
bool controlsAdded = false;
try
{
base.CreateChildControls();
SPWeb theWeb = new SPSite(this.SiteURL).OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(theWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[this.Text];
if (list.BaseTemplate == SPListTemplateType.GenericList)
{
this.lblError = new Label();
this.lblError.Text = "Error:";
this.lblError.Visible = true;
HtmlTable child = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
string str = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.CSSField + "\" /><script type=\"text/javascript\" src=\"/_layouts/NewsViewer/jquery-1.3.2.min.js\"></script><script type=\"text/javascript\">var X = jQuery.noConflict();X(document).ready(function() {\t X(\".main_image .desc\").show(); X(\".main_image .block\").animate({ opacity: 0.85 }, 1 ); X(\".image_thumb ul li:first\").addClass('active'); X(\".image_thumb ul li\").click(function(){ var imgAlt = X(this).find('img').attr(\"alt\"); var imgTitle = X(this).find('a').attr(\"href\"); var imgDesc = X(this).find('.block').html(); \t var imgDescHeight = X(\".main_image\").find('.block').height();\t\t if (X(this).is(\".active\")) { return false; } else { X(\".main_image .block\").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { X(\".main_image .block\").html(imgDesc).animate({ opacity: 0.85,\tmarginBottom: \"0\" }, 250 ); X(\".main_image img\").attr({ src: imgTitle , alt: imgAlt}); }); } X(\".image_thumb ul li\").removeClass('active'); X(this).addClass('active'); return false;}) .hover(function(){ X(this).addClass('hover'); }, function() { X(this).removeClass('hover');}); X(\"a.collapse\").click(function(){ X(\".main_image .block\").slideToggle(); X(\"a.collapse\").toggleClass(\"show\"); });}); </script><div id=\"main\" class=\"container\">";
string sideNav = this.GetSideNav();
string mainContent = this.GetMainContent();
cell.InnerHtml = str + mainContent + sideNav + "</div></div>";
row.Cells.Add(cell);
child.Rows.Add(row);
this.Controls.Add(child);
controlsAdded = true;
}
}
}
});
}
catch (Exception exception)
{
if (controlsAdded)
{
this._exceptions = this._exceptions + "CreateChildControls_Exception: " + exception.Message;
}
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Error: " + exception.Message;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
}
if (!controlsAdded)
{
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Please choose the Personal Announcement list: " + this.Text + " - Site:" + this.SiteURL;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
else
{
cell.InnerHtml = "Please setup Personal Announcement by clicking Modify Shared WebPart";
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
}
}
private string FirstWords(string input, int numberWords)
{
try
{
int num = numberWords;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ' ')
{
num--;
}
if (num == 0)
{
return input.Substring(0, i);
}
}
}
catch (Exception)
{
}
return string.Empty;
}
private string GetMainContent()
{
string str = "";
this.lblError.Text = this.lblError.Text + " -> GetMainContent()";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
view.RowLimit = 1;
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num == 0)
{
object obj2;
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
str2 = str2 + "<div class=\"main_image\">";
str2 = str2 + "<img src=\"" + imageURL + "\" alt=\"BNNewsbanner\" />";
str2 = str2 + "<div class=\"desc\" >Close Me!";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No Title Text Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
// str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
}
num++;
}
}
str = str + str2;
}
}
return str;
}
public int getNumber(string number)
{
switch (number)
{
case "One":
return 1;
case "Two":
return 2;
case "Three":
return 3;
case "Four":
return 4;
case "Five":
return 5;
case "Six":
return 6;
case "Seven":
return 7;
case "Eight":
return 8;
case "Nine":
return 9;
case "Ten":
return 10;
}
return 0;
}
private string GetSideNav()
{
this.lblError.Text = this.lblError.Text + " -> GetSideNav()";
string str = "<div class=\"image_thumb\"><ul>";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num < num2)
{
object obj2;
string imageThumbURL = "";
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
if (item[this.ThumbImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString();
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else
{
imageThumbURL = this.ImageThumbURL;
}
str2 = str2 + "<li><a href=\"" + imageURL + "\">";
str2 = str2 + "<img src=\"" + imageThumbURL + "\" alt=\"\" /></a>";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No List Title Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
}
num++;
}
}
str = str + str2;
}
}
return (str + "</ul>");
}
public override ToolPart[] GetToolParts()
{
ToolPart[] partArray = new ToolPart[3];
WebPartToolPart part = new WebPartToolPart();
CustomPropertyToolPart part2 = new CustomPropertyToolPart();
partArray[0] = part2;
partArray[1] = part;
partArray[2] = new CustomToolPart();
return partArray;
}
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception exception)
{
this._exceptions = this._exceptions + "RenderContents_Exception: " + exception.Message;
}
finally
{
if (this._exceptions.Length > 0)
{
writer.WriteLine(this._exceptions);
}
}
}
private string StripTagsCharArray(string source)
{
char[] chArray = new char[source.Length];
int index = 0;
bool flag = false;
for (int i = 0; i < source.Length; i++)
{
char ch = source[i];
if (ch == '<')
{
flag = true;
}
else if (ch == '>')
{
flag = false;
}
else if (!flag)
{
chArray[index] = ch;
index++;
}
}
return new string(chArray, 0, index);
}
// Properties
public string BodyField
{
get
{
return this.startField;
}
set
{
this.startField = value;
}
}
[WebDisplayName("Style Sheet URL"), WebDescription("Specifies the path to the css file"), SPWebCategoryName("General Settings"), Personalizable(true), WebBrowsable(true)]
public string CSSField
{
get
{
return this.sTimeField;
}
set
{
this.sTimeField = value;
}
}
[WebBrowsable(true), Personalizable(true), WebDisplayName("Date Format"), WebDescription("Date Format of your News Items"), SPWebCategoryName("General Settings")]
public TheDateFormat DateFormat
{
get
{
return this.DF;
}
set
{
this.DF = value;
}
}
[WebBrowsable(true), WebDescription("Thumb Image URL to use when no image is found"), SPWebCategoryName("General Settings"), Personalizable(true), WebDisplayName("No Thumb Image URL")]
public string ImageThumbURL
{
get
{
return this.sTImageURL;
}
set
{
this.sTImageURL = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebBrowsable(true), WebDisplayName("No Image URL"), WebDescription("Image URL to use when no image is found")]
public string ImageURL
{
get
{
return this.sImageURL;
}
set
{
this.sImageURL = value;
}
}
public string ImageURLField
{
get
{
return this.endField;
}
set
{
this.endField = value;
}
}
public string ListViewFields
{
get
{
return this.listViewFields;
}
set
{
this.listViewFields = value;
}
}
[WebDescription("Number of news items to show"), WebDisplayName("Number of news items to show"), WebBrowsable(true), SPWebCategoryName("General Settings"), Personalizable(true)]
public PeriodEnum NumEvents
{
get
{
return this.Period;
}
set
{
this.Period = value;
}
}
[WebDisplayName("Number of words to show from the Body"), Personalizable(true), SPWebCategoryName("General Settings"), WebDescription("Specifies the number of words to show from the body in the main webpart, under the Title"), WebBrowsable(true)]
public string NumWords
{
get
{
return this.sYAxisTitle;
}
set
{
this.sYAxisTitle = value;
}
}
public string SiteURL
{
get
{
return this.siteURLtext;
}
set
{
this.siteURLtext = value;
}
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebDisplayName("Image Column Type")
You can put the code in CreateChildControls() method.

span insertion logic help

I have a text like this
"You are advised to grant access to these settings only if you are sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access."
and i have 3 selections,
1. StartIndex = 8, Length = 16 // "advised to grant"
2. StartIndex = 16, Length = 33 //"to grant access to these settings"
3. StartIndex = 35, Length = 26 // "these settings only if you"
i need to insert span tags and highlight selections, and intersections of words should be highlighted in different color,
result should be something like this
"You are <span style= 'background-color:#F9DA00'>advised </span> <span id = 'intersection' style= 'background-color:#F9DA00'>to grant </span> <span style= 'background-color:#F9DA00'>advised </span> <span style= 'background-color:#F9DA00'>access to </span>
<span id = 'intersection' style= 'background-color:#F9DA00'>these settings</span>
<span style= 'background-color:#F9DA00'>only if you </span> sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access."
please help me to sort this out, i have been trying to figure-out a logic for a long time now and no luck so far
Markup comment: IDs need to be unique. Make them classes instead: class="intersection".
finally manage to find a solution on my own, hope this help someone also in the future
public enum SortDirection
{
Ascending, Descending
}
public enum SpanType
{
Intersection, InnerSpan, Undefined
}
class Program
{
static void Main(string[] args)
{
string MessageText = #"You are advised to grant access to these settings only if you are sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access.";
List<Span> spanList = new List<Span>();
List<Span> intersectionSpanList = new List<Span>();
spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = SpanType.Undefined, StartIndex = 8, Length = 16 });
spanList.Add(new Span() { SpanID = "span2", Text = "to grant access to these settings", ElementType = SpanType.Undefined, StartIndex = 16, Length = 33 });
spanList.Add(new Span() { SpanID = "span3", Text = "these settings only if you", ElementType = SpanType.Undefined, StartIndex = 35, Length = 26 });
// simple interseciotn
//spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = TagType.Undefined, StartIndex = 8, Length = 16 });
//spanList.Add(new Span() { SpanID = "span2", Text = "to grant access", ElementType = TagType.Undefined, StartIndex = 16, Length = 15 });
// two different spans
//spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = TagType.Undefined, StartIndex = 8, Length = 16 });
//spanList.Add(new Span() { SpanID = "span2", Text = "only if you are ", ElementType = TagType.Undefined, StartIndex = 50, Length = 16 });
// inner span
//spanList.Add(new Span() { SpanID = "span1", Text = "to grant access to these settings", ElementType = TagType.Undefined , StartIndex = 16, Length = 33 });
//spanList.Add(new Span() { SpanID = "span2", Text = "access to these", ElementType = TagType.Undefined, StartIndex = 25, Length = 15 });
// one inner span, and complex
//spanList.Add(new Span() { SpanID = "span1", Text = "to grant access to these settings only ", ElementType = TagType.Undefined, StartIndex = 16, Length = 39 });
//spanList.Add(new Span() { SpanID = "span2", Text = "access to these", ElementType = TagType.Undefined, StartIndex = 25, Length = 15 });
//spanList.Add(new Span() { SpanID = "span3", Text = "only if you are sure", ElementType = TagType.Undefined, StartIndex = 50, Length = 20 });
// one large span, and two intersections
//spanList.Add(new Span() { SpanID = "span1", Text = "grant access to these settings only if you are sure you want to allow this program to run automatically when", ElementType = SpanType.Undefined, StartIndex = 19, Length = 108 });
//spanList.Add(new Span() { SpanID = "span2", Text = "these settings only", ElementType = SpanType.Undefined, StartIndex = 35, Length = 19 });
//spanList.Add(new Span() { SpanID = "span3", Text = "you want to allow this", ElementType = SpanType.Undefined, StartIndex = 71, Length = 22 });
spanList.Sort("StartIndex asc");
foreach (var item in spanList)
item.SplitSpans(ref spanList, ref intersectionSpanList, ref MessageText);
// join intersections with span collection
foreach (var item in intersectionSpanList)
spanList.Add(item);
//remove duplicates
spanList = RemoveDuplicateSpans(spanList);
// sort spans by index ..
spanList.Sort("StartIndex asc"); //desc
foreach (var item in spanList)
{
item.InsertStartSpan(ref spanList, ref MessageText);
}
foreach (var item in spanList)
{
item.InsertEndSpan(ref spanList, ref MessageText);
}
//int count = spanList.Count -1;
//while (count > 0)
//{
// Span currentSpan = spanList[count];
// currentSpan.InsertEndSpan(ref spanList, ref MessageText);
// count--;
//}
}
internal static List<Span> RemoveDuplicateSpans(List<Span> list)
{
List<int> uniqueList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count ; j++)
{
if (list[i].SpanID != list[j].SpanID)
{
if (list[i].StartIndex == list[j].StartIndex && list[i].EndPossition == list[j].EndPossition && list[i].ElementType == SpanType.Undefined)
{
uniqueList.Add(i);
}
}
}
}
foreach (var item in uniqueList)
{
list.RemoveAt(item);
}
return list;
}
}
public static class Extensions
{
public static void Sort<T>(this List<T> list, string sortExpression)
{
string[] sortExpressions = sortExpression.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
List<GenericComparer> comparers = new List<GenericComparer>();
foreach (string sortExpress in sortExpressions)
{
string sortProperty = sortExpress.Trim().Split(' ')[0].Trim();
string sortDirection = sortExpress.Trim().Split(' ')[1].Trim();
Type type = typeof(T);
PropertyInfo PropertyInfo = type.GetProperty(sortProperty);
if (PropertyInfo == null)
{
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo info in props)
{
if (info.Name.ToString().ToLower() == sortProperty.ToLower())
{
PropertyInfo = info;
break;
}
}
if (PropertyInfo == null)
{
throw new Exception(String.Format("{0} is not a valid property of type: \"{1}\"", sortProperty, type.Name));
}
}
SortDirection SortDirection = SortDirection.Ascending;
if (sortDirection.ToLower() == "asc" || sortDirection.ToLower() == "ascending")
{
SortDirection = SortDirection.Ascending;
}
else if (sortDirection.ToLower() == "desc" || sortDirection.ToLower() == "descending")
{
SortDirection = SortDirection.Descending;
}
else
{
throw new Exception("Valid SortDirections are: asc, ascending, desc and descending");
}
comparers.Add(new GenericComparer { SortDirection = SortDirection, PropertyInfo = PropertyInfo, comparers = comparers });
}
list.Sort(comparers[0].Compare);
}
}
public class GenericComparer
{
public List<GenericComparer> comparers { get; set; }
int level = 0;
public SortDirection SortDirection { get; set; }
public PropertyInfo PropertyInfo { get; set; }
public int Compare<T>(T t1, T t2)
{
int ret = 0;
if (level >= comparers.Count)
return 0;
object t1Value = comparers[level].PropertyInfo.GetValue(t1, null);
object t2Value = comparers[level].PropertyInfo.GetValue(t2, null);
if (t1 == null || t1Value == null)
{
if (t2 == null || t2Value == null)
{
ret = 0;
}
else
{
ret = -1;
}
}
else
{
if (t2 == null || t2Value == null)
{
ret = 1;
}
else
{
ret = ((IComparable)t1Value).CompareTo(((IComparable)t2Value));
}
}
if (ret == 0)
{
level += 1;
ret = Compare(t1, t2);
level -= 1;
}
else
{
if (comparers[level].SortDirection == SortDirection.Descending)
{
ret *= -1;
}
}
return ret;
}
}
public class Span
{
string _Color = "#F9DA00";
public const int SPAN_START_LENGTH = 40;
public const int SPAN_END_LENGTH = 7;
public const int SPAN_TOTAL_LENGTH = 47;
public string Color
{
get
{
return _Color;
}
set
{
_Color = value;
}
}
public string SpanID { get; set; }
public int StartIndex { get; set; }
public int HTMLTagEndPossition { get; set; }
public Span ParentSpan { get; set; }
public int Length { get; set; }
public SpanType ElementType { get; set; }
public string Text { get; set; }
public int EndPossition
{
get
{
return StartIndex + Length;
}
}
public string GetStartSpanHtml()
{
return "<span style= 'background-color:" + Color + "'>" + this.Text;
}
public string GetEndSpanHtml()
{
return "</span>";
}
public bool IsProcessed { get; set; }
internal void PostProcess(Span span, ref List<Span> spanList, ref string MessageText)
{
MessageText = MessageText.Remove(span.StartIndex, span.Length);
MessageText = MessageText.Insert(span.StartIndex, span.GetStartSpanHtml());
int offset = Span.SPAN_TOTAL_LENGTH;
AdjustStartOffsetOfSpans(spanList, span, offset);
}
internal void SplitSpans(ref List<Span> spanList, ref List<Span> intersectionSpanList, ref string MessageText)
{
foreach (var item in spanList)
{
if (this.SpanID == item.SpanID)
continue;
if (this.StartIndex < item.StartIndex && this.EndPossition > item.EndPossition)
{
// inner
int innerSpanLength = this.EndPossition - item.StartIndex;
int innerSpanStartPos = this.StartIndex;
string innerSpanText = MessageText.Substring(item.StartIndex, item.Length);
Span innerSpan = new Span();
innerSpan.SpanID = "innerSpan" + Guid.NewGuid().ToString().Replace("-", "");
innerSpan.ElementType = SpanType.InnerSpan;
innerSpan.Text = innerSpanText;
innerSpan.Length = item.Length;
innerSpan.StartIndex = item.StartIndex;
innerSpan.ParentSpan = this;
intersectionSpanList.Add(innerSpan);
}
if (this.StartIndex < item.StartIndex && item.EndPossition > this.EndPossition && this.EndPossition > item.StartIndex)
{
// end is overlapping
int intersectionLength = this.EndPossition - item.StartIndex;
int intersectionStartPos = item.StartIndex;
string intersectionText = MessageText.Substring(item.StartIndex, intersectionLength);
// Build intersection span
Span intersectonSpan = new Span();
intersectonSpan.SpanID = "intersectonSpan" + Guid.NewGuid().ToString().Replace("-", "");
intersectonSpan.Text = intersectionText;
intersectonSpan.Length = intersectionLength;
intersectonSpan.StartIndex = intersectionStartPos;
intersectonSpan.ElementType = SpanType.Intersection;
intersectionSpanList.Add(intersectonSpan);
// adjust my end pos.
this.Length = this.Length - intersectionLength;
this.Text = this.Text.Substring(0, this.Length);
item.StartIndex += intersectionLength;
item.Length -= intersectionLength;
item.Text = item.Text.Substring(intersectionLength, item.Length);
}
else if (this.StartIndex < item.StartIndex && item.EndPossition > this.EndPossition && this.EndPossition < item.StartIndex)
{
// two spans are not over lapping,
}
//if (this.EndPossition > item.StartIndex && this.EndPossition < item.EndPossition)
//{
// if (item.StartIndex < this.StartIndex && item.EndPossition > this.EndPossition)
// {
// int innerSpanLength = this.EndPossition - this.StartIndex;
// int innerSpanStartPos = this.StartIndex;
// string innerSpanText = MessageText.Substring(this.StartIndex, this.Length);
// // we are dealing with a inner span..
// Span innerSpan = new Span();
// innerSpan.SpanID = "innerSpan";
// innerSpan.Text = innerSpanText;
// innerSpan.Length = innerSpanLength;
// innerSpan.StartIndex = innerSpanStartPos;
// innerSpan.IsIntersection = true;
// intersectionSpanList.Add(innerSpan);
// MessageText = MessageText.Remove(innerSpanStartPos, innerSpanLength);
// MessageText = MessageText.Insert(innerSpanStartPos, innerSpan.GetStartSpanHtml());
// break;
// }
// int intersectionLength = this.EndPossition - item.StartIndex;
// int intersectionStartPos = item.StartIndex;
// string intersectionText = MessageText.Substring(item.StartIndex, intersectionLength);
// // adjust the string.
// if (!this.IsProcessed)
// {
// this.Text = this.Text.Substring(0, this.Length - intersectionLength);
// this.Length = this.Length - intersectionLength;
// MessageText = MessageText.Remove(this.StartIndex, this.Length);
// MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
// // readjust intersection after insertion of the first span..
// intersectionStartPos = Span.SPAN_START_LENGTH + intersectionStartPos;
// }
// // Build intersection span
// Span intersectonSpan = new Span();
// intersectonSpan.SpanID = "intersectonSpan";
// intersectonSpan.Text = intersectionText;
// intersectonSpan.Length = intersectionLength;
// intersectonSpan.StartIndex = intersectionStartPos;
// intersectonSpan.IsIntersection = true;
// intersectionSpanList.Add(intersectonSpan);
// MessageText = MessageText.Remove(intersectionStartPos, intersectionLength);
// MessageText = MessageText.Insert(intersectionStartPos, intersectonSpan.GetStartSpanHtml());
// if (!this.IsProcessed)
// item.StartIndex = item.StartIndex + intersectionLength + Span.SPAN_START_LENGTH + Span.SPAN_START_LENGTH;
// else
// item.StartIndex = item.StartIndex + intersectionLength + Span.SPAN_START_LENGTH;
// item.Length = item.Length - intersectionLength;
// item.Text = item.Text.Substring(intersectionLength, item.Length);
// //MessageText = MessageText.Remove(item.StartIndex, item.Length);
// //MessageText = MessageText.Insert(item.StartIndex, item.GetOuterHtml());
// int offset;
// if (!this.IsProcessed)
// offset = Span.SPAN_START_LENGTH + Span.SPAN_START_LENGTH;
// else
// offset = Span.SPAN_START_LENGTH;
// AdjustOffsetSpans(spanList, item, offset);
// this.IsProcessed = true;
// break;
//}
//else if (item.StartIndex > this.StartIndex && item.EndPossition < this.EndPossition)
//{
// // bigger span, inside there are children span(s)
// MessageText = MessageText.Remove(this.StartIndex, this.Length);
// MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
// // since this span is the big guy.
// AdjustOffsetForInnerSpansAndExternalSpans(spanList, this, this.StartIndex, this.EndPossition);
// this.StartIndex += Span.SPAN_START_LENGTH;
// this.IsProcessed = true;
//}
}
}
//internal static void AdjustOffsetForInnerSpansAndExternalSpans(List<Span> spanList, Span parentSpan, int parentStartIndex, int parentEndIndex)
//{
// bool adjustAfterThisSpan = false;
// foreach (var item in spanList)
// {
// if (item.SpanID == parentSpan.SpanID)
// {
// adjustAfterThisSpan = true;
// continue;
// }
// if (adjustAfterThisSpan)
// {
// // is this span in the middle of the parent ?
// if (item.StartIndex > parentSpan.StartIndex && item.EndPossition < parentSpan.EndPossition)
// {
// item.StartIndex += SPAN_START_LENGTH;
// }
// else
// {
// // after parent tag ?
// item.StartIndex += SPAN_START_LENGTH;
// }
// }
// }
//}
private void AdjustEndOffsetOfSpans(List<Span> spanList, Span span, int SPAN_END_LENGTH)
{
bool adjustAfterThisSpan = false;
foreach (var item in spanList)
{
if (item.SpanID == span.SpanID)
{
adjustAfterThisSpan = true;
continue;
}
if (adjustAfterThisSpan)
{
if (item.ParentSpan == null)
{
item.HTMLTagEndPossition += SPAN_END_LENGTH;
}
else if (span.ParentSpan != null && this.SpanID == item.ParentSpan.SpanID)
{ }
}
}
}
internal static void AdjustStartOffsetOfSpans(List<Span> spanList, Span fromSpan, int offset)
{
bool adjustAfterThisSpan = false;
foreach (var item in spanList)
{
if (item.SpanID == fromSpan.SpanID)
{
adjustAfterThisSpan = true;
continue;
}
if (adjustAfterThisSpan)
item.StartIndex += offset;
}
}
internal void InsertStartSpan(ref List<Span> spanList, ref string MessageText)
{
MessageText = MessageText.Remove(this.StartIndex, this.Length);
MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
AdjustStartOffsetOfSpans(spanList, this, SPAN_START_LENGTH);
// Adjust end element tag
switch (this.ElementType)
{
case SpanType.Intersection:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
break;
}
case SpanType.InnerSpan:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
// increase the parent's tag offset conent length
this.ParentSpan.HTMLTagEndPossition += SPAN_START_LENGTH;
break;
}
case SpanType.Undefined:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
break;
}
default:
break;
}
}
internal void InsertEndSpan(ref List<Span> spanList, ref string MessageText)
{
switch (this.ElementType)
{
case SpanType.Intersection:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
case SpanType.InnerSpan:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
case SpanType.Undefined:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
default:
break;
}
AdjustEndOffsetOfSpans(spanList, this, SPAN_END_LENGTH);
}
}

Resources