How to display contact name or display_name of contact in list off messeges - android-studio

How could I display the names of the following numbers in my Listview if the numbers are given in the loop.
void FetchAllMessages(){
msgList = new ArrayList<>();
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor.moveToFirst()) {
do {
String from = cursor.getString(cursor.getColumnIndex("address"));
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(from));
Cursor phones = getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phones.moveToFirst()){
contactname = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
msgList.add(contactname);
}else{
msgList.add(from);
}
} while (cursor.moveToNext());
}
}
There is no display in my android and it continue to crash.
Any help is much appreciated.

It seems you didn't write code for no contacts check. Try this code
ContentResolver cr = cntx.getApplicationContext().getContentResolver();
//Query to get contact name
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
// If data data found in contacts
ArrayList<String> msgList = new ArrayList<String>();
if (cur.getCount() > 0) {
int k = 0;
String name = "";
while (cur.moveToNext()) {
String id = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[]{id},
null);
int j = 0;
while (pCur
.moveToNext()) {
// Sometimes get multiple data
if (j == 0) {
// Get Phone number
phoneNumber = "" + pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber.startsWith("+91")) {
phoneNumber = phoneNumber.substring(3, phoneNumber.length());
}
phoneNumber = phoneNumber.replaceAll("\\s", "");
if (phoneNumber.length() == 10) {
// Add contacts names to arrayList
msgList.add(name.toString());
}
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();

Related

Add Join in BQLCommand

I would like to join the following statement with EPEmployee table on EPEmployee's BAccountID with FSAppointmentEmployee's EmployeeID column then put where condition on EPEmployee's UserID with currently logged in employee's user id in the current BQLCommand for PXAdapter, so that I can see the list of appointments that are assigned to current employee only.
public static PXAdapter PrepareCustomNavAdapter(PXAction action, PXAdapter adapter, bool prevNextAction = false)
{
var select = adapter.View.BqlSelect;
select = select
.WhereAnd<Where<EPEmployee.userID,Equal<AccessInfo.userID>>>()
.OrderByNew<OrderBy<
Desc<FSAppointment.createdDateTime,
Desc<FSAppointment.srvOrdType,
Desc<FSAppointment.refNbr>>>>>();
var newAdapter = new PXAdapter(new PXView(action.Graph, true, select))
{
MaximumRows = adapter.MaximumRows
};
object current = action.Graph.Views[action.Graph.PrimaryView].Cache.Current;
if (prevNextAction)
{
var sortColumns = new string[adapter.SortColumns.Count() + 1];
adapter.SortColumns.CopyTo(sortColumns, 1);
sortColumns[0] = "CreatedDateTime";
newAdapter.SortColumns = sortColumns;
var descendings = new bool[adapter.Descendings.Count() + 1];
adapter.Descendings.CopyTo(descendings, 1);
descendings[0] = true;
newAdapter.Descendings = descendings;
var searches = new object[adapter.Searches.Count() + 1];
adapter.Searches.CopyTo(searches, 1);
if (current != null && current is FSAppointment)
searches[0] = ((FSAppointment)current).CreatedDateTime;
newAdapter.Searches = searches;
}
else if (current != null)
{
adapter.Currents = new object[] { current };
}
return newAdapter;
}
So that, only these two employees would be able to see that appointment.
Thank you.
AccessInfo is a Singleton, you should decorate it with Current class:
Where<EPEmployee.userID, Equal<Current<AccessInfo.userID>>>

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

Update a SavedQuery (View) from the SDK

I am trying to change all the Business Unit references I got after importing a solution to the ones in the Acceptance environment.
QueryExpression ViewQuery = new QueryExpression("savedquery");
String[] viewArrayFields = { "name", "fetchxml" };
ViewQuery.ColumnSet = new ColumnSet(viewArrayFields);
ViewQuery.PageInfo = new PagingInfo();
ViewQuery.PageInfo.Count = 5000;
ViewQuery.PageInfo.PageNumber = 1;
ViewQuery.PageInfo.ReturnTotalRecordCount = true;
EntityCollection retrievedViews = service.RetrieveMultiple(ViewQuery);
//iterate though the values and print the right one for the current user
int oldValues = 0;
int accValuesUpdated = 0;
int prodValuesUpdated = 0;
int total = 0;
foreach (var entity in retrievedViews.Entities)
{
total++;
if (!entity.Contains("fetchxml"))
{ }
else
{
string fetchXML = entity.Attributes["fetchxml"].ToString();
for (int i = 0; i < guidDictionnary.Count; i++)
{
var entry = guidDictionnary.ElementAt(i);
if (fetchXML.Contains(entry.Key.ToString().ToUpperInvariant()))
{
Console.WriteLine(entity.Attributes["name"].ToString());
oldValues++;
if (destinationEnv.Equals("acc"))
{
accValuesUpdated++;
Console.WriteLine();
Console.WriteLine("BEFORE:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.AccGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
Console.WriteLine();
Console.WriteLine("AFTER:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
}
else
{
prodValuesUpdated++;
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.ProdGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
}
service.Update(entity);
}
}
}
}
Console.WriteLine("{0} values to be updated. {1} shall be mapped to acceptance, {2} to prod. Total = {3} : {4}", oldValues, accValuesUpdated, prodValuesUpdated, total, retrievedViews.Entities.Count);
I see that the new value is corrected, but it does not get saved. I get no error while updating the record and publishing the changes in CRM does not help.
Any hint?
According to your comments, it sounds like the value you're saving the entity as, is the value that you want it to be. I'm guessing your issue is with not publishing your change. If you don't publish it, it'll still give you the old value of the FetchXml I believe.
Try calling this method:
PublishEntity(service, "savedquery");
private void PublishEntity(IOrganizationService service, string logicalName)
{
service.Execute(new PublishXmlRequest()
{
ParameterXml = "<importexportxml>"
+ " <entities>"
+ " <entity>" + logicalName + "</entity>"
+ " </entities>"
+ "</importexportxml>"
});
}

How to read values from dictionary value collection and make it comma seperated string?

I have a dictionary object as under
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();
dictStr.Add("Culture", new List<string>() { "en-US", "fr-FR" });
dictStr.Add("Affiliate", new List<string>() { "0", "1" });
dictStr.Add("EmailAddress", new List<string>() { "sreetest#test.com", "somemail#test.com" });
And I have an entity as under
public class NewContextElements
{
public string Value { get; set; }
}
What I need to do is that for every value in a particular index of the dictionary value collection, I have to make a comma separated string and place it into List collection.
e.g. the NewContextElements collection will have (obviously at run time)
var res = new List<NewContextElements>();
res.Add(new NewContextElements { Value = "en-US" + "," + "0" + "," + "sreetest#test.com" });
res.Add(new NewContextElements { Value = "fr-FR" + "," + "1" + "," + "somemail#test.com" });
I was trying as
var len = dictStr.Values.Count;
for (int i = 0; i < len; i++)
{
var x =dictStr.Values[i];
}
no it is of-course not correct.
Help needed
Try this:
Enumerable.Range(0, len).Select( i =>
new NewContextElements {
Value = string.Join(",", dictStr.Values.Select(list => list[i]))
}
);
len is the number of items inside the individual lists (in your example, it's two).
This isn't a slick as #dasblinkenlight's solution, but it should work:
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>( );
dictStr.Add( "Culture", new List<string>( ) {"en-US", "fr-FR"} );
dictStr.Add( "Affiliate", new List<string>( ) {"0", "1"} );
dictStr.Add( "EmailAddress", new List<string>( ) {"sreetest#test.com", "somemail#test.com"} );
int maxValues = dictStr.Values.Select(l => l.Count).Max();
List<NewContextElements> resultValues = new List<NewContextElements>(dictStr.Keys.Count);
for (int i = 0; i < maxValues; i++) {
StringBuilder sb = new StringBuilder();
string spacer = string.Empty;
dictStr.Keys.ForEach( k => {
sb.AppendFormat( "{0}{1}", spacer, dictStr[k][i] );
spacer = ", ";
} );
resultValues.Add( new NewContextElements( ){ Value = sb.ToString() });
}
do you mean transform your data like
1 2
3 4
5 6
to
1 3 5
2 4 6
try this block of code? it can be optimized in a few ways.
var res = new List<NewContextElements>();
int i = dictStr.values.count()
for (int i=0; i < len; i++) {
NewContextElements newContextElements = new NewContextElements();
foreach (List<string> list in dictStr) {
if (newContextElements.value() == null ) {
newContextElements.value = list[i];
} else {
newContextElements.value += ", " + list[i] );
}
}
res.add(newContextElements);
}
let me know if there are problems in the code, most like there is when you write it without a real ide.

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