Substring from the beginning of a word - c#

The HTTP GET response for a request is like below
<html>
<head> <script type="text/javascript">----</script> <script type="text/javascript">---</script> <title>Detailed Notes</title>
</head>
<body style="background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000"> <p>this is one note </p> </body> </html>
I am getting this as a string and i have to read the body part out of it.
I tried HtmlAgility pack, but HTML parsing is getting failed due to some specials in the html content (I think something from the commented script causing this issue).
So to read the tag content i am thinking of a SubString operation.
Like SubString from the beginning of <body tag.
How can we do SubString from the beginning of a word from a text?

Using a simple SubString() with IndexOf() + LastIndexOf():
string BodyContent = input.Substring(0, input.LastIndexOf("</body>") - 1).Substring(input.IndexOf("<body"));
BodyContent = BodyContent.Substring(BodyContent.IndexOf(">") + 1).Trim();
This will return:
<p> this is one note </p>
string FullBody = input.Substring(0, input.LastIndexOf("</body>") + 7).Substring(input.IndexOf("<body")).Trim();
This will return:
<body style = background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000' >< p > this is one note </p> </body>

The " will cause a problme so you need to replace every " after you get the request source
WebClient client = new WebClient(); // make an instance of webclient
string source = client.DownloadString("url").Replace("\"",",,"); // get the html source and escape " with any charachter
string code = "<body style=\"background-color: #FFFFFF; border-width: 0px; font-family: sans-serif; font-size: 13; color: #000000\"> <p>this is one note </p> </body>";
MatchCollection m0 = Regex.Matches(code, "(<body)(?<body>.*?)(</body>)", RegexOptions.Singleline); // use RE to get between tags
foreach (Match m in m0) // loop through the results
{
string result = m.Groups["body"].Value.Replace(",,", "\""); // get the result and replace the " back
}

Related

Print rich text string with all effect and styles in pdf using iTextSharp

I am trying to print rich text content in pdf using itextSharp library with version 5.5.8.0. But I am I am printing that rich text, it will print only normal string without any style effect or html tags.
Here is my web view that contain rich text
But while printing in pdf using iTexhSharp, it will print like rich text but each html element it will start printing with new line, as like below image
Here is the code, that I am using to print rich text in pdf:
ElementList elements = XMLWorkerHelper.ParseToElementList(descriptionData, "");
PdfPCell cell = new PdfPCell();
foreach(var ele in elements) {
cellDescriptionData.AddElement(ele);
}
tableThirdBlock.AddCell(cellDescriptionData);
Here the "descriptionData" field will contain the html string.
I want to be print the same in pdf as available in web view.
Here is the actual HTML string, which is generated dynamically. So the html string will be dynamic with dynamic css and text.
" <b style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal; color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);">zzz </b><div style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal;"><b style="color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);"><br /></b></div><div><b style="font-family: Arial, Verdana; font-size: 10pt; font-style: normal; font-variant: normal; font-weight: normal; line-height: normal; color: rgb(204, 255, 255); background-color: rgb(51, 102, 255);">Test </b> <span style="color: rgb(255, 0, 0);"> <span style="font-weight: bold;">Description</span> </span><span style="color: rgb(153, 51, 153); font-style: italic;">Other Color</span></div> ".
Is anything wrong, that I am missing ?
Please help me to print rich text with all effect and styles in pdf.
Thanks
I your comment, you are asking for an example on how to use XML Worker to parse HTML to a list of Element objects. Such an example can be found on the official iText web site in the answers to question such as:
How to adjust the page height to the content height? 1
How to convert Arabic HTML to PDF? 2
In 1, you'll discover that you can parse an HTML and CSS file to an ElementList object:
ElementList elements = XMLWorkerHelper.parseToElementList(HTML, CSS);
In 2, you'll learn how to add the elements in an ElementList to a PdfPCell:
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
for (Element e : elements) {
cell.addElement(e);
}
table.addCell(cell);
document.add(table);
Note that I simplified the examples from the original questions. You don't need RTL because your text probably isn't Arabic. You can probably use the convenience method parseToElementList() instead of using the full code that was used in 2.
I have created a proof of concept that results in the file test-herin.pdf:
The HTML to get this result looks like this:
<div><span class="bluetextwhitebackground">zzz</span></div>
<div>
<span class="bluetextwhitebackground">Test</span>
<span class="redtext">Description</span>
<span class="italicpurple">Other Color</span>
</div>
The CSS to get the desired styles looks like this:
.bluetextwhitebackground
{ font-family: times; color: white; background: blue}
.redtext
{ font-family: times; color: red; }
.italicpurple
{ font-family: times; font-style: italic; color: purple }
As you can see, I used <div> when I want a block of text that causes a new line after the text is rendered. I used <span> in cases where I don't want a new line to appear.
It is hard to answer your question because you don't show your HTML. New lines are triggered when using <p> or <div> tags, or by defining something as a div in the CSS.
By the way, the code to generate the PDF can be found here: ParseHtml13
Update:
After you shared the HTML, I created another proof of concept:
The resulting PDF file is test-herin2.pdf and it looks like this:
This looks exactly the way I expect it. In other words: I can't reproduce the problem you're describing. If I can't reproduce a problem, I can't fix it.

Getting dynamically added labels to look like tags

What I'd like to do is have something similar to what SO does on the main page:
So, what I did was add this code:
C# Code-Behind:
protected void LoadInterests()
{
//Fill Interests based on table values
string strSQL2 = "SELECT UM.MatchValue, DD.DDLValue FROM tmpUsermatch UM ";
strSQL2 = strSQL2 + "INNER JOIN (SELECT StoredValue, DDLValue FROM tmpDropdowns WHERE ddlName = 'ddlInterests') DD ";
strSQL2 = strSQL2 + "ON UM.MatchValue = DD.StoredValue ";
strSQL2 = strSQL2 + "WHERE MatchField = 'MatchInterests' AND UserID = '" + lblUserID.Text + "'";
using (var con = new SqlConnection(strCon1))
using (var adapter2 = new SqlDataAdapter(strSQL2, con))
{
DataTable dt2 = new DataTable();
adapter2.Fill(dt2);
foreach (DataRow row in dt2.Rows)
{
Label dynamicLabel = new Label();
dynamicLabel.ID = "lbl" + row["DDLValue"].ToString();
dynamicLabel.Text = row["DDLValue"].ToString();
dynamicLabel.CssClass = "lbl.interests";
div1.Controls.Add(dynamicLabel);
}
}
}
asp.net:
<div>
<asp:Panel ID="Panel1" runat="server" Height="100px" ScrollBars="Vertical" Style="float: left; margin-left: 1px; background-color:#f5f5f5" Width="807px" BorderColor="LightSteelBlue" BorderStyle="Solid" BorderWidth="1px">
<div id="div1" runat="server" class="clear" style="width:820px; border-width:1px; margin-left:20px"></div>
</asp:Panel>
</div>
CSS:
lbl.interests
{
background-color: #465c71;
/* background-color: white; */
border: 1px #4e667d solid;
color: white;
display: block;
line-height: 1.35em;
padding: 4px 20px;
text-decoration: none;
white-space: nowrap;
}
The end result is still this:
when I want it to look like this:
Any ideas on where I'm going wrong?
Change the line
dynamicLabel.CssClass = "lbl.interests";
to
dynamicLabel.CssClass = "lbl interests";
AND change CSS selector to
.lbl.interests
Remember . is used for selecting class name only in CSS, it will not be present in HTML, also if you specify just name in css like lbl you are referring to a TAG in HTML which is invalid tag according to HTML and also does match with the code.
My suggestion would be first write plain HTML and CSS and confirm your layout is working as expected, then generate the HTML with C#/ASP.Net
Refer the below link for help on CSS Selectors
W3Schools - CSS Selectors

Invalid length for a Base-64 char array or string c# mvc4 web Api

I am using swift 2.0 and Alamofire 3.0. I made a POST request with Alamofire. Parameters in my request contained text and a base64 encoded image. But I am getting a Message as response saying "An error occurred". Asp.net mmvc4 web api is used as backend. The base64 string seems too long. by using an online text editor editpad. in that I found that the character count of my base64 string is 4405562 Characters (including whitespace)
Image to base64 code (swift 2)
var userProfileImage : String = ""
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let capturedImage : UIImage
if let _image = info["UIImagePickerControllerEditedImage"] as? UIImage
{
capturedImage = _image
self.profilePicture.image = _image
let imagetosave = UIImageJPEGRepresentation(_image, 1.0)
let base64encodedImage = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
}
}
else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
{
capturedImage = _image
var __image = UIImageJPEGRepresentation(_image,1.0)
let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
self.profilePicture.image = _image
}
else
{
return
}
dismissViewControllerAnimated(true, completion: nil)
}
Alamofire POST Request
let params = ["userid":"\(user)" , "firstname":"\(String(_firstName))" , "middlename":"\(String(_middlename))","lastname":"\(String(_lastname))","password":"\(String(_pass))","email":"\(String(_email))","oldpassword":"\(_oldpass)","base64String":"userProfileImage"]
Alamofire.request(.POST, App.AppHomeURL() + "Update_Profile", parameters : params , encoding : .JSON).responseJSON{
response in
switch response.result {
case .Success(let data) :
let json = JSON(data)
let _data : String = json["Data"].string!
if (_data == "true")
{
let _storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let _profile = _storyBoard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(_profile, animated: true)
}
Here I get the JSON response as "Message" : "An error has occurred"
Backend code that receives the POST request
public JsonResult Update_Profile([FromBody]UpdateProfileViewModel updateprofileviewmodel)
{
//code goes here
if (updateprofileviewmodel.base64String != "" && updateprofileviewmodel.base64String != null && updateprofileviewmodel.base64String != "null")
{
byte[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
string filenametosave = usermodel._id + "." + System.Drawing.Imaging.ImageFormat.Jpeg;
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/FridgeUserProfilePictures/" + filenametosave);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
image.Save(path);
usermodel.Photo = filenametosave;
}
}
here in the line byte[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
an exception occurs saying
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Invalid length for a Base-64 char array or string.
EDIT :
Just put the Base64 string got from Swift in a variable in webApi method
var base64String = "Base64 string got in ios"
this worked and created an image in server.
I tried using POSTMAN a google extension. on using it I found that the actual String is not getting passed. say the string length is 100 on passing only string with length 50 is send and produced the error mentioned in the Question. later I tried this and the response is
response = Optional(<NSHTTPURLResponse: 0x7fe593618b30> { URL: http://app.appurl } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 3420;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Dec 2015 11:59:22 GMT";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} })
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
<style>
body {
font-family: "Verdana";
font-weight: normal;
font-size: .7em;
color: black;
}
p {
font-family: "Verdana";
font-weight: normal;
color: black;
margin-top: -5px
}
b {
font-family: "Verdana";
font-weight: bold;
color: black;
margin-top: -5px
}
H1 {
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red
}
H2 {
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon
}
pre {
font-family: "Consolas", "Lucida Console", Monospace;
font-size: 11pt;
margin: 0;
padding: 0.5em;
line-height: 14pt
}
.marker {
font-weight: bold;
color: black;
text-decoration: none;
}
.version {
color: gray;
}
.error {
margin-bottom: 10px;
}
.expandable {
text-decoration: underline;
font-weight: bold;
color: navy;
cursor: hand;
}
#media screen and (max-width: 639px) {
pre {
width: 440px;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
#media screen and (max-width: 479px) {
pre {
width: 280px;
}
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
)
May not be the answer for you but I did this,
Compress the Image before sending it to the server and now everything works fine.

I want to get the ID of label using C# which is being created by jQuery on RunTime

First I will explain my scenario.
I have asp.net menu (dynamically created menu) and now I want to place push notification just like Facebook on my each menu option. I have designed it using CSS and put a label using jQuery.
if (res == "MenuIcons") {
$(this.parentElement).addClass('Notification');
var $label = $("<label ID=\"notificationlbl" + i + "\" style=\"position: absolute; margin-top: 2%; margin-left: -3.1%; margin-right:-3.3%; z-index: 99; color: white; font-size: 9px; font-family: Verdana; letter-spacing: -1px;\">").text('99');
$(this.parentElement.parentElement).append($label);
i++;
}
But I am totally confused that how to handle it using C# because I am unable to get the ID of the label created on run-time.
If you didn't understand please let me know and I will explain it more.
why don't you set a data attribute to each label, something like
var $label = $("<label data-element-type='notification' ID=\"notificationlbl" + i + "\" style=\"position: absolute; margin-top: 2%; margin-left: -3.1%; margin-right:-3.3%; z-index: 99; color: white; font-size: 9px; font-family: Verdana; letter-spacing: -1px;\">").text('99');
and then you can retrieve the whole collection with jQuery:
$("[data-element-type='notification']").each(function(){...});
Try adding runat="server" attribute in your label tag. You label tag id won't be available until runtime. So what you can do is search for the controllers by the id of your label. In code behind you can do as following
foreach(Contol c in this.Controls)
{
if(c.ID.contains("notificationlbl")
{
//your code
}
}

Dynamic text underlined by braces

I want to underline a word with a round brace. This should be part of a C# Text but if it is easier in CSS, no problem. My problem is that the length of the Word can vary, so the bow must by calculated for each word.
My first idea was using CSS box-shadow:
CSS:
#test {
font-size: 50px;
background: transparent;
border-radius: 70px;
height: 65px;
width: 90px;
box-shadow: 0px 6px 0px -2px #00F;
font-family: sans-serif;
}
HTML:
<div id="test">Hey</div>
Unfortunately due to the dynamic Text sizes I can't calculate them.
Is there a smarter approach to this problem?
You don't need to calculate the width if you use span tags instead.
CSS:
.test {
font-size: 50px;
background: transparent;
border-radius: 70px;
height: 65px;
box-shadow: 0px 6px 0px -2px #00F;
font-family: sans-serif;
}
HTML:
<span id="test" class="test">Hey</span><br/>
<span class="test">Hey this is longer</span>
Working Fiddle: http://jsfiddle.net/Ge8Q3/
I found a different approach.
Working fiddle: http://jsfiddle.net/6pEQA/1/
I used javascript and made the width dynamic:
textWidth function taken from here.
$.fn.textWidth = function(){
var self = $(this),
children = self.contents(),
calculator = $('<span style="white-space:nowrap;" />'),
width;
children.wrap(calculator);
width = children.parent().width(); // parent = the calculator wrapper
children.unwrap();
return width;
};
$(document).ready(function(){
$('#test').css('width',$('#test').textWidth());
});
It also works with h1, div or span. You can check my fiddle. Because it is using span elements to calculate width of the element.

Categories