.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

return a TextPointer to an arbitrary character position N?

Posted By:      Posted Date: September 26, 2010    Points: 0   Category :WPF


I would like to return the TextPointer to an arbitrary (nth) character position (including whitespace) of RichTextBox XAML.

Given "Mary had a little lamb".  I would like to return a text pointer corresponding to the letter position 8, (in this case, I would get a TextPointer for the insertion point just before the letter 'd' in 'had'). This would need to ignore any formatting elements and other UI elements in the xml anywhere in the text.

 I think this would be similar to the method


but which ignores all symbols other than character data (recalling that GetPositionAtOffset includes all "symbols", not only text).

Performance: I realize that I could write a function which moves a TextPointer one position at a time and inspects what type of symbol is found at each spot and stops when it gets to the Nth character. But that seems very expensive. I am hoping there is a built in function which is more performant. (and I would really have thought this might be part of the System.Windows.Documents  API)

 thanks very much.

View Complete Post

More Related Resource Links

Find the position of a character



we are working with sql server 2005. My xml comes like this:

<ImportResponse xmlns="aaa:import:response:1.0" timestamp="2010-09-24T15:38:40">
<Summary failures="2" successes="3">
 <Message code="-304" level="error">One or more errors have occurred while processing the
  request items
 <Result id="50063,123" success="false">
    <Message code="-1100" level="error">Invalid field format (knect) - The Value fails meets the
     requirements for this field: MaximumLength=9, Precision=0 - {3}
 <Result id="50064,124" success="false">
    <Message code="-1100" level="error">Invalid field format (knect) - The Value fails meets the requirements for this
  field: MaximumLength=9, Precision=0 - {3}


I need to remove the value after ',' from Result element ID attribute. I need to do this

reading TXT file with (èàò) and return strange character

  Private Function Traduci(ByVal file As String)

    Dim testo As String = My.Computer.FileSystem.ReadAllText(file)

    Dim righe As String()
    righe = Split(testo, vbCrLf)

    For i As Integer = 0 To righe.Length - 1

  End Function<br/>

i am trying to read an TXT fiel with this function
in my example.txt i have this row:"pèpòàèpòàpèòp+p"

but the program returns": p?p???p??p??p+p"
is the charset the problem? if yes where can i set it?


ListView DataPager with SQL-Statements that already return only paged data.



As far as I understand the ListView-Control and the DataPager-Control, they work like this: The ListView gets its datarows from its data source, then the DataPager causes the ListView to display only a subset of those rows.

So what, when I want to use custom databinding for the ListView, that *already* gets the certain subset from SQL-Server (for better performance). Can I and how can I use the DataPager then?

Thanx, S.

How to position one control relative to another one even after resizing windows?


I used following Jquery code trying to make image close to a table. It worked fine after first load, but the position changed after window is resized. Any ideas? thanks

$(document).ready(function() {
            var pos = $("#mytable").offset();
            var width = $("#mytable").width();
            var left = pos.left + width + 20;
            var top = pos.top + 200;
                position: 'absolute',
                zIndex: 5000,
                left: left,
                top: top

WebMatrix conversion failed when converting from a character string to uniqueidentifier?


I am trying to retrieve xml from a small function in my .cshtml page. Its throwing me an error. This however, runs fine in a console/form environment.

It takes 3 parameters and 1 exception.

myDll.GetXML(year, username, uniqueidentifier, out ex);

When I run this page I get the error, "Conversion failed when converting from a character string to uniqueidentifier."

Or a stack of.

System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting from a character string to uniqueidentifier.

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)

   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()

   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)

   at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()

   at System.Data.SqlClient.SqlDataReader.get_MetaData()

   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)

   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBeha

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

XMLHTTP.ResponseText return unexecuted code?


I have a simple asp with the following code.  When I access this page directly (via browser) everything works fine:  the xml object shows up fine.  When I call this page via VBA (excel), the ResponseText method of the 

XMLHTTP object returns the below code unexecuted.  Anybody knows what's going on?  thanks.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <% Response.Buffer = True Response.ContentType = "text/xml" Dim oDataXML As Object 'Custom Data XML passed in by caller. On Error Resume Next 'Load the XML passed into the request. oDataXML = Server.CreateObject("Microsoft.XMLDOM") oDataXML.Load(Request) Dim sResult As String sResult = "<?xml version=""1.0""?>" sResult = sResult & "<OrderProcessed>" sResult = sResult & "<Status>test</Status>" sResult = sResult & "<OrderID>111</OrderID>" sResult = sResult & "</OrderProcessed>" Response.Write(sResult) Response.End() %>

Composite Control which contains arbitrary content defined in .aspx of parent and thier ViewState


I want to write own control which can contain other. And I want to define content of the control in the .aspx file where the control is defined. I have written such control. But now I have issue with ViewState of inner controls of my control. The following samle illustrates the issue: I defined two asp:DropDownList ID="ddl1" and ID="ddl2" One of them is inside of my control and other is outside. When posback is occurred asp:DropDownList ID="ddl1 loses state and becomes empty. How to say ASP.net to store state of inner controls defined by this way?


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="DynamicControls.Controls.MyControl" %>

<div class="box">
    <div class="Header-Left">
        <div class="Header-Right">
            My Control
    <div class="Content">
        <asp:PlaceHolder ID="contentPlace" runat="Server" />

Posting data to ASMX and return Object for jQuery


I am using fluent NHibernate with WebForms and I am trying to build a page where I allow a user to post a status update on their profile page and I a using a .asmx WebService to post the data to the database and then returnig a StatusUpdate instance to the page to be used by jQuery. I have a couple problems.

1) First off when I return a string from the WebService(i was testing) the textbox where the user enters their status doesnt empty the contents. And since the page doesnt refresh even if I manally clear out the textbox and put in something else, it still posts the previous status to the database again. How do I fix this?

2) Secondly, when I return the StatusUpdate Object from the Webservice I cant the results to display anything. Like I sad, Im using jQuery to make an AJX call to the WebService.

Here is my code:

User Profile Page:

Status: <asp:Label ID="status" runat="server"></asp:Label><span style="font-size:.7em;"><asp:Label ID="statustime" runat="server"></asp:Label></span><br />
<textarea id="statusBox" rows="3" cols="40"></textarea><br />
<input type="button" value="Update Status" onclick="SetStatus(); return false;

Web Deployment Projects (WDP) arabic character



I built web project using asp.net & c# in VS2005 and i use arabic label in my project and every think working good when i run my application. but when i use WDP to make msi file All arabic letter come like ?????. 


Return of the Rich Client: Code Access Security and Distribution Features in .NET Enhance Client-Sid


Rich clients employ many of the features and conveniences of the operating system they run on, and the list of these features has been growing since the dawn of the PC. But as apps have migrated to the Web, the trend towards increasing client-side functionality has ground to a virtual halt. There are several reasons for this; chief among them are security and deployment problems. But that's all about to change. With the .NET Framework, you can participate in building the distributable rich client of the future. In this article, the author enumerates the pertinent features of .NET that will allow you to build safe, easily deployable controls. The features discussed include managed code, code access security, versioning control, Windows Forms classes, and isolation.

Jason Clark

MSDN Magazine June 2002

SQL and XML: Use XML to Invoke and Return Stored Procedures Over the Web


Front-end developers frequently want to add functionality to the presentation tier of an n-tier architecture, but such requests can require changes on all tiers just to get the data and present it. This process can be made easier and more flexible by using SQL Server stored procedures to automate the delivery of data in XML format from the database to the front-end components. In the component presented here, stored procedures are invoked by XML strings, XML is returned, converted using XSL, and presented to the client in HTML. The technique supports rapid changes yet doesn't sacrifice the n-tier approach. This approach can be used with either SQL Server 7.0 or SQL Server 2000.

Dave Grundgeiger, Anson Goldade, and Varon Fugman

MSDN Magazine August 2001

DirectX 8.0: Enhancing Real-Time Character Animation with Matrix Palette Skinning and Vertex Shaders


DirectX 8.0 allows the creation of smooth and realistic character movements that are more life-like than simple articulated structure animations. This is made possible by its improved support for vertex tweening and blended vertex deformations, also known as soft-skinning. After a brief history of the use of these techniques in DirectX, soft-skinning using the fixed function pipeline is discussed. This is followed by the use of matrix palettes from within vertex shaders to create a customized soft-skinning solution that takes advantage of the benefits of vertex shaders, such as hardware acceleration and custom lighting algorithms without the limitations of fixed-function solutions.

Benjamin Freidlin

MSDN Magazine June 2001

linq and max, if return null return error


hi there
i have this query :

var result2 = (from TH in DB.Threshold
                          where TH.ProductSKUID == int.Parse(HID_ProductSKUID.Value)
                          select TH.ThresholdID).Max();

the problem is that if this query does not find any items, return null, so thow exception
how can i do to return 0??

Return a file with bad headers?


I've build a MP4Handler. The Mp4 hander selects a correct file from a url.
The system works if you work with 'normal' mp4 files.

But the problem is the MP4 files are genrated by another program, so i think there's the problem.
Right now i returned a test file, then it woks great!

Do i return the other file, i get a 412 error if i use it in IE (he shows a  400 error because i deleted the 412 error in the IIS i thought maybe that solves the problem) . In IE it doesn't work, but in firefox it works great!

In my Fiddler result, the first movie (guid url) is from firefox, and works great. The second with the text/html result (selected row) is from IIS.
How can i solve this problem?

Or is this the problem?:
This entity tag is not recognized by IIS. It only affects version 7.0 of the IIS software.
From: http://www.pc-library.com/errors/error-code/412-0x19C/ 


As coding i use this as base: http://dotnetslackers.com/articles/aspnet/Range-Specific-Requests-in-ASP-NET.aspx 
I changed The GetRequestedFileInfo with:
public override FileInfo GetRequeste

setting scroll position for a ListBox


I have a ListBox control showing 10 rows.  I have 30 rows total in the listbox.  How do I programmatically adjust the scroll to show the last ten rows?

Some sources have suggested that I set the SelectedItem.  But I am already making selections (myListBox.Items[28].Selected = true, myListBox.Items[29].Selected = true, etc); the listbox scroll is positioned on Item[0] not the first selected item.  I have also tried setting myListBox.SelectedItem in addition to the multiple selection just mentioned but that does not have any affect either.


Linq join fields for return data


  how would I join fields together?

           return (from c in storedb.Product_Categories

                         where c.Category_Name.Contains(searchText)
                         orderby c.Category_Name
                         select new {
                                    c.Category_Key && " ;" && c.Category_Name // HOW CAN I DO THIS.....

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend