Posts

Showing posts from May, 2016

Donate

CookieContainer - Part Of Cookie Is Invalid In C# Cookies And WebResponse

Given the code below when scraping a website, you might encounter an error which is stated in the title of the post that is Part Of Cookie Is Invalid . 1 2 3 4 5 6 7 8 9 10 11 WebRequest request = WebRequest.Create( "http://your_url_here" ); WebResponse webResponse = request.GetResponse(); if (webResponse.Headers[ "Set-Cookie" ] != null ) { Cookie m_ccCookies = new Cookie(); CookieContainer ccContainer = new CookieContainer(); ccContainer = new CookieContainer(); ccContainer.SetCookies(webResponse.ResponseUri, webResponse.Headers[ "Set-Cookie" ]); ccContainer.Add(ccContainer.GetCookies(webResponse.ResponseUri)); } The issue could be that the url domain cookie value which is passed to SetCookies method have unrecognized characters that needs to be encoded. So, the workaround is to encode the cookie value first and then assign the appropriate encoding before saving it to the cookie container object. 1 2 ccC

Get Total Hours And Minutes From Total Minutes Using TimeSpan Class In C# And VB.NET

Image
Good evening! Given total number of minutes as input and you need to extract the total number of hours and remaining minutes out from the input, you need to use the TimeSpan class specifically FromMinutes() method. Based from the docs ,the FromMinutes method returns a TimeSpan object that represents a specified number of minutes, where the specification is accurate to the nearest millisecond. C# Code 1 2 3 4 TimeSpan span = TimeSpan.FromMinutes(1506); var hours = ( int ) span.TotalHours; var minutes = span.Minutes; Console.WriteLine(hours + ":" + minutes.ToString( "D2" )); VB.NET Code 1 2 3 4 Dim span As TimeSpan = TimeSpan.FromMinutes(1506) Dim hours = CInt (span.TotalHours) Dim minutes = span.Minutes Console.WriteLine(hours + ":" + minutes.ToString( "D2" )) Output

ASP.NET MVC ListBoxFor() With Optgroup Tag Support

Image
Here's a simple ListBoxFor helper that supports optgroup tag. See versions for C# and VB.NET. C# Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public static class HtmlExtensions { public static IHtmlString ListBoxFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Dictionary< string , IEnumerable<SelectListItem>> selectList, object htmlAttributes = null ) { var select = new TagBuilder( "select" ); select .Attributes.Add( "name" , ExpressionHelper.GetExpressionText(expression)); if (htmlAttributes != null ) { RouteValueDictionary routeValues = new RouteValueDictionary(htmlAttributes); if (!routeValues.ContainsKey(( "size" ).ToLower(

Failed to load resource: the server responded with a status of 404 (WebResource.axd)

I downloaded a GridView custom control with cool features on search and filtering that was developed on Visual Studio 2010 and ASP.NET 4.0. After playing around with the control, I decided to migrate the files to Visual Studio 2012 ASP.NET 4.5. Upon running the ASP.NET Project, the resource to be embedded on the GridView control in which case a JavaScript file was not recognized/found. And thus, returned a 404 status. After doing some research, I came up with the solution below. Steps to fix the issue: 1. Set Build Action of the Resource/JavaScript file to Embedded Resource . In my project, the file to be embedded is EnhancedGridView.js 2. Add WebResourceAttribute to the GridView custom control to embedded a JavaScript file as Resource in an assembly. Make sure that the namespace of the file is correct. 1 2 3 4 5 [assembly: WebResource("GridViewFilter.EnhancedGridView.js", "text/javascript")] public partial class EnhancedGridView : GridView { //.....

Remove Formatting Of Last Selected Text In A WPF RichTextBox Control

Image
Here's how to remove the formatting of last selected text in a WPF RichTextBox control from it's SelectionChanged event. C# Code 1 2 3 4 5 6 private void rtbEditor_SelectionChanged( object sender, RoutedEventArgs e) { //Clear previous selections. TextRange textRange = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd); textRange.ClearAllProperties(); } Output

Create XmlElement Using XmlSerializer In C#.NET

Image
Given the XML data below, the product properties are generated below the products node. What I want is to structure the product properties inside an element Product while serializing. <?xml version="1.0" encoding="utf-8"?> <Products xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "http://www.w3.org/2001/XMLSchema" > <Code>12345</Code> <Name>Samsung Galaxy</Name> <Model>Galaxy</Model> <Manufacturer>Samsung Ltd</Manufacturer> <OperatingSystem>Jelly Bean</OperatingSystem> <Distributor>Junrex</Distributor> <Version>7.0</Version> </Products> To achieve that, I have modified the model classes by separating the properties into another class and in the Products class I created a property of type List with XML Attribute Product . public class Products { [XmlElement("Product")] publ

Parse Html Table Using HTML Agility Pack In C#

Below is a simple code to parse a table using HTML Agility Pack. Make sure to add the Html Agility Pack package from Nuget and reference that library in the namespace of your program. 1 using HtmlAgilityPack; Parse Table 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load( "http://your_sample_url" ); // Get all tables in the document HtmlNodeCollection tables = doc.DocumentNode.SelectNodes( "//table" ); // Iterate all rows in the first table HtmlNodeCollection rows = tables[0].SelectNodes( "tr" ); for ( int i = 0; i <= rows.Count - 1; i++) { // Iterate all columns in this row HtmlNodeCollection cols = rows[i].SelectNodes( "td" ); if (cols != null ) { for ( int j = 0; j <= cols.Count - 1; j++) { // Get the value of the column and print it string value = cols[j].InnerText; Console.Write

Removing Hyperlink Or LinkButton In A GridViewColumn Based From A Condition Or Value

Image
There was a question raised from the forum on how to remove a hyperlink control in a GridViewColumn if a given condition is met. In the example below, the hyperlink(LinkButton) is disabled if Units In Stock is zero (0). A solution is to disable the LinkButton in the RowDataBoundEvent . 1 2 3 4 5 6 7 8 9 10 11 protected void gvUnitSummary_RowDataBound( object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (Convert.ToInt32(e.Row.Cells[3].Text) == 0) { LinkButton lnkUnitID = (LinkButton)e.Row.FindControl( "lnkProducts" ); lnkUnitID.Enabled = false ; } } } Another solution is to change the column from BoundField to TemplateField. The TemplateField contains a LinkButton and a Label control. Set the Visibility property of the controls accordingly such as LinkButton will be shown if Units In Stock is greater than 0. Otherwise, show the Label control instead. 1 2

Donate