Menu
  • HOME
  • TAGS

Why am I not able to consistently have a `HashTable` serialized?

Tag: asp.net,vb.net

Yesterday I wrote a web method to return reported problems:

<WebService(Namespace:="http://maggie/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class _Raphael
    Inherits System.Web.Services.WebService

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function GetReportedProblems(ByVal pathname As String) As Hashtable

When I try to use the web method I get the following error:

The type System.Collections.Hashtable is not supported because it implements IDictionary.

A quick google search made me realize that I'm apparently not supposed to be able to get a HashTable serialized by .Net without me having to do some work.

My confusion stems from the fact that I usually use HashTable objects as a return from my web methods (mostly because it's pretty close to a JavaScript object, and pretty convenient).

An example of a web method I wrote returning a HashTable (which is working perfectly fine):

<ScriptService()> _
Partial Class _Lugash_Gopher
    Inherits ppcBasePage 'which inherits System.Web.UI.Page

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Shared Function GetAgentsPaged(ByVal iDisplayStart As Integer, ByVal iDisplayLength As Integer, ByVal sEcho As Integer, ByVal TeamID As Integer) As Hashtable

I populate the HashTable (h) like so:

h.Add("TeamID", TeamID) 'Integer
h.Add("sEcho", sEcho)   'Integer (blame DataTables.Net for the "s" prefix)
h.Add("iTotalRecords", iTotalRecords) 'Integer
h.Add("iTotalDisplayRecords", iTotalDisplayRecords) 'Integer
h.Add("aaData", Helpers.ConvertDataTableToJSON(ds.Tables(1))) 'Method returns System.Array

which returns (example):

{
    "d": {
        "iTotalRecords": 2,
        "iTotalDisplayRecords": 10,
        "team_name": "All Teams",
        "aaData": [{
            "next_due_date": "01/01/2014",
            "ready_feedback": 0,
            "emp_name": "John Doe",
            "row": 1,
            "incomplete_feedback": 1,
            "emp_id": 1
        }, {
            "next_due_date": "01/14/2014",
            "ready_feedback": 0,
            "emp_name": "Jane Smith",
            "row": 2,
            "incomplete_feedback": 1,
            "emp_id": 2
        }],
        "sEcho": 1,
        "TeamID": 1
    }
}

The method GetReportedProblems is housed in a .asmx code-behind and allows for a GET.

The method GetAgentsPaged is housed in a .aspx code-behind and requires POST.

These are the only two differences that I can determine in the method structures.

Why am I able to use a HashTable as a return type for a web method in a .aspx code-behind, but not in a a .asmx code-behind?

Best How To :

I found the answer to your problem here in this fórum. But part of that answer you already found out by your self, from what you describe.

So the next big question you ask is, so how come, that a simple ASPX can do the job that an ASMX can't? The answer for this is because ASMX is XML based mainly, all the communication with ASMX is based on SOAP. For it to work, with ASP.NET via ScriptManager (which I believe is what you are doing) Microsoft cleverly developed and Handler:

(...) To enable Web service calls from script, you must register the ScriptHandlerFactory HTTP handler in the application's Web.config file. The handler processes calls made from script to .asmx Web services. The following example shows the Web.config element for adding the handler.(...)

But for the rest of the time, the web service is still XML based, like is supposed to:

(...) For Web service calls that are not issued from ASP.NET AJAX script, the ScriptHandlerFactory handler delegates the call to the default handler, which uses SOAP instead of JSON format. The delegation is performed automatically and you do not have to take any action unless you want to disable the use of the SOAP protocol for the Web services. In that case, you must enter the following configuration setting in the Web.config file. (...)

(...) To enable an .asmx Web service to be called from client script in an ASP.NET Web page, you must add a ScriptManager control to the page. You reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and then setting the server reference path attribute to the URL of the Web service. The ServiceReference object instructs ASP.NET to generate a JavaScript proxy class for calling the specified Web service from client script. (...)

Note: this information was extracted from here.

Continuing, so why do you receive that error in ASMX Web Service? Well you receive that error because the compiler is telling you this "Hey, when someone calls me (xml web service), most of the times I will probably respond in XML and Hashtables which implement IDictionary are not convertible to XML!", if you had some way to tell the compiler "Hey, but I promise to call you (xml ws) only from an ASP.NET page via ScriptManager which talks with you via a Proxy implemented by an ASP.NET Handler" then your code would work, but ASMX WebService doesn't allow you to perform such kind of configuration!

And that's why XML WebServices (asmx) trows that error, and ASP.NET do not, because ASP.NET does not respond in XML, it responds in what you want it to respond, since the developer can arbitrarily decide whether he want to send responses JSON, HTML, XML, Text or just binary based.

If I were you, I would take a little step forward and I would try to specify that your Web Method outputs XML (in your ASP.NET Page), to see if it throws you the same error, I haven't tried this, but most certainly that is what will happen.

Update 1

Note that the tag ScriptService does not specify inheritance, it is just an annotation, probably that is how the ScriptHandler detects a call to an XML WebService that it should intercept! The nature of your class is defined by its inheritance which is based on the WebService class (specific to XML WebServices). And so the preceding annotations of this type 'ScriptMethod' are also specific to the ScriptHandler as they specify what should it do to convert the answer of the Web Service in order to send it to your ScriptManager registered in your ASP.NET page!

If you feel that Web Services should do more for you I advise you strongly to look at WCF Services aka Indigo Services (Codename), you can find more info about this here. After you try this, you will never use XML WebServices again :), it has a little learning curve in the configuration part but after that is pure quality of work! A good book for you to read about WCF is this WCF by Jonh Sharp, in my personal opinion of course. And btw, very good and pertinent question!

Update 2

Stating a similar response to mine here, it says:

(...) The service exposed to JavaScript via [ScriptMethod] uses a different serializer (the JavaScriptSerializer), which does not have this limitation.

When you call the service from JavaScript, you invoke the JSON endpoint (declared with [ScriptMethod]). When you test from the browser, however, you reach the traditional XML enpoint (declared with [WebMethod]). (...)

An workaround would be for you to use JavaScriptSerializer to serialize the Hashtable to JSON (inside the web method), then your web method would return a String, but this is kind of... bad! And you would be probably better served with WCF Services if you intent to build something both maintainable and scalable.

Update 3

To better direct my answer to your comment bellow, yes, you can't serialize Hashtables because "XmlSerializer cannot process classes implementing the IDictionary interface" (XML WebServices at some instance, end up using the XML Serializer, and that's when the exception is thrown from the bottom of the stack, until it reaches your code):

(...) Q: Why can't I serialize hashtables? A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface. (...)

This excerpt was taken from this Microsoft Resource here, it's near the bottom of the page.

How to pass all value of ListBox Control to a function?

vb.net,listbox

You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting. You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String...

Access manager information from Active Directory

c#,asp.net,active-directory

try this: var loginName = @"loginNameOfInterestedUser"; var ldap = new DirectoryEntry("LDAP://domain.something.com"); var search = new DirectorySearcher(ldap) { Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))" }; var result = search.FindOne(); if (result == null) return; var fullQuery = result.Path; var user = new DirectoryEntry(fullQuery); DirectoryEntry manager; if (user.Properties.PropertyNames.OfType<string>().Contains("manager")) { var managerPath...

Retrieve data from one table and insert into another table

sql,asp.net,sql-server

INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee INNER JOIN tbl2...

Visual Basic Datagrid View change row colour

vb.net,datagridview,datagrid

Is it possible that your datagridview isn't loaded fully when you try to recolor the rows? Since you are setting the datasource, you should put your code that affects the grid after you can make sure that it is finished loading. The column widths change because it is not dependent...

Server side session in asp.net

asp.net,web-services,session

You've got a quotes problem, fix it like this: <% Session["path"] = "'" + vr_ + "'"; %> EDIT 1: Javascript and ASP.NET are not the same, so you cannot access the variables, so you can't do it on the client side. You must send something to the server like...

how can i use parameters to avoid sql attacks

sql,vb.net

I think the only solution is create a new function and gradually migrate to it. Public Function ExecuteQueryReturnDS(ByVal cmdQuery As SqlCommand) As DataSet Try Dim ds As New DataSet Using sqlCon As New SqlConnection(connStr) cmdQuery.Connection = sqlCon Dim sqlAda As New SqlDataAdapter(cmdQuery) sqlAda.Fill(ds) End Using Return ds Catch ex As...

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce

Your missing an @symbol for the id attribute: Modify your script as well like this: ***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name ** you can use the # to denote and ID in Jquery by the...

Difference between application and module pipelines in Nancy?

c#,asp.net,nancy

The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

How do I use VB.NET to send an email from an Outlook account?

vb.net,email

change the smtpserver from smtp.outlook.com to smtp-mail.outlook.com web.config settings <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network host="smtp-mail.outlook.com" userName="[email protected]" password="passwordhere" port="587" enableSsl="true"/> </smtp> </mailSettings> ...

Removing Alert When Using DeleteFile API

vb.net,vba,api,delete

There are several SHFILEOPSTRUCT.fFlags options you'll want to consider. You are asking for FOF_NOCONFIRMATION, &H10. You probably want some more, like FOF_ALLOWUNDO, FOF_SILENT, FOF_NOERRORUI, it isn't clear from the question. Check the docs.

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

Connecting to database using Windows Athentication

sql-server,vb.net,authentication,connection-string

You need to add Integrated Security=SSPI and remove username and password from the connection string. Dim ConnectionString As String = "Data Source=Server;Initial Catalog=m2mdata02;Integrated Security=SSPI;" ...

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of...

How do ASP.NET Web APIs work once built with MSBUILD?

c#,asp.net,msbuild

The WebApi is a web project and on compiling it creates a dll. It is not a class library or a nuget package to consume and use it. I have practically implemented this in a real world application and below are my thoughts for your understanding. Your question is Once...

Get XML node value when previous node value conditions are true (without looping)

xml,vb.net,linq-to-xml

UPDATE Using an XDocument vs an XmlDocument, I believe this does what you're asking without using loops. This is dependent on the elements being in the order of <PhoneType> <PhonePrimaryYN> <PhoneNumber> string xml = "<?xml version=\"1.0\"?>" + "<Root>" + " <PhoneType dataType=\"string\">" + " <Value>CELL</Value>" + " </PhoneType>" + "...

WCF service architecture query

asp.net,architecture,wcfserviceclient

As long as you are able to use the exact same contract for all the versions the web application does not need to know which version of the WCF service it is accessing. In the configuration of the web application, you specify the URL and the contract. However, besides the...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6

Ideally what you want is a many-to-many relationship between your Shop and Product entities: public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;}...

Trigger a js function with parameter from code behind

c#,jquery,asp.net,scriptmanager,registerstartupscript

All you need to do is add a semi-colon to the end of your String.Format call. ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptManager1", String.Format(@"ShowHideMessageBlock('{0}');", @"#successMsg"), true); ...

.NET wep api won't accept %2E or . in api request uri

c#,jquery,asp.net,ajax,json

Have a look at this answer MVC4 project - cannot have dot in parameter value? Try changing the Web.Config file <system.web> <httpRuntime relaxedUrlToFileSystemMapping="true" /> </system.web> ...

Get List of Elements in Tree with specific Field Value

vb.net,linq,properties,interface

If i have understood it correctly you want to get all selected parents and all selected children. You could use a recursive method: Public ReadOnly Property checkedList As List(Of TreeSelectorAttributes) Get Return rootList.Where(Function(t) t.SelectedInTreeSelector). SelectMany(Function(root) GetSelectedChildren(root)). ToList() End Get End Property Function GetSelectedChildren(root As TreeSelectorAttributes, Optional includeRoot As Boolean =...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

onSuccess and onFailure doesn't get fired

javascript,c#,asp.net,webmethod,pagemethods

You PageMethod is looking like this PageMethods.LoginUser(onSuccess, onFailure, email, pass); And when you call it, it looks like this PageMethods.LoginUser(email, pass); Your arguments should be in the same order as the method. PageMethods.LoginUser(email, pass, onSuccess, onFailure); ...

How to make a website work only with https [duplicate]

asp.net,ssl,https

Sure, assuming you are using IIS to host your site, open IIS Manager and select your web site and then binding on the right: make sure you only have a binding for https not for http. This way IIS will only send https traffic to that web site. Edit: What...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

add BR between text in dynamically created control

c#,asp.net

You need to use InnerHtml property HtmlGenericControl li = new HtmlGenericControl("li"); li.ID = "liQuestions" + recordcount.ToString(); li.Attributes.Add("role", "Presentation"); ULRouting.Controls.Add(li); HtmlGenericControl anchor = new HtmlGenericControl("a"); li.Attributes.Add("myCustomIDAtribute", recordcount.ToString()); anchor.InnerHtml = "Test <br/> 12345"; li.Controls.Add(anchor); Or, like this: anchor.Controls.Add(new LiteralControl("Test")); //or new Literal("Test"); anchor.Controls.Add(new HtmlGenericControl("br"));...

Retrieve full path of FTP file on drag & drop?

vb.net,ftp

If the data dropped contains a UniformResourceLocator format, you can get the entire URL from that, for example: Private Sub Form1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop If e.Data.GetDataPresent("UniformResourceLocator") Then Dim URL As String = New IO.StreamReader(CType(e.Data.GetData("UniformResourceLocator"), IO.MemoryStream)).ReadToEnd End If End Sub It first checks to see if a...

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc

You are using a namespace, your full type name is Project.ViewModel.ViewModel (namespace is Project.ViewModel and class name is ViewModel) so use this using instead: @model Project.ViewModel.ViewModel ...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model

You need to pass the model instance to the view: Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View(employee) End Function ...

VB.Net DateTime conversion

jquery,vb.net,datetime

System.Globalization.DateTimeFormatInfo.InvariantInfo doesn't contain format pattern dd-MM-yyyy(26-06-2015) From MSDN about InvariantCulture The InvariantCulture property can be used to persist data in a culture-independent format. This provides a known format that does not change For using invariant format in converting string to DateTime your string value must be formatted with one of...

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

c#,asp.net,sql-server,date,gridview-sorting

What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

ZipEntry() and converting persian filenames

vb.net,persian,sharpziplib

Try setting IsUnicodeText to true: 'VB.NET Dim newEntry = New ZipEntry(entryName) With { _ Key .DateTime = DateTime.Now, _ Key .Size = size, _ Key .IsUnicodeText = True _ } //C# var newEntry = new ZipEntry(entryName) { DateTime = DateTime.Now, Size = size, IsUnicodeText = true }; ...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

Filtering Last Duplicate Occurrence In A Datatable

c#,vb.net

You can use LINQ: DataTable nonDups = parsedDataset.Tables("Detail").AsEnumerable() .GroupBy(row => row.Field<string>("Authorization_ID")) .OrderBy(grp => grp.Key) .Select(grp => grp.Last()) .CopyToDataTable(); This selects the last row of each dup-group. If you want to order the group use grp.OrderBy....

Return index of word in string

arrays,vb.net,vbscript

Looking at your desired output it seems you want to get the index of word in your string. You can do this by splitting the string to array and then finding the item in an array using method Array.FindIndex: Dim animals = "cat, dog, bird" ' Split string to array...

Can I uniquely identify 2 check boxes so that I can add a different image to each?

html,css,asp.net,checkbox

Here is an example of what I meant: (Oh and, forgive the images please :) ) #field1,#field2{ display:none; } #field1 + label { padding:40px; padding-left:100px; background:url(http://www.clker.com/cliparts/M/F/B/9/z/O/nxt-checkbox-unchecked-md.png) no-repeat left center; background-size: 80px 80px; } #field1:checked + label { background:url(http://www.clker.com/cliparts/B/2/v/i/n/T/tick-check-box-md.png) no-repeat left center; background-size: 80px 80px; } #field2 + label { padding:40px;...

asp.net background in 3 pieces to be stationary

html,css,asp.net

I would use a separate div and use fixed positioning on it. Example <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Layout Example</title> <link rel="stylesheet" type="text/css" href="./Layout Example_files/style.css"> <style type="text/css"> .fixed-background{ background: url( "images/SoapBubbles.jpg" ) no-repeat fixed top center; position:fixed; z-index:-1; top:0; right:0; left:0; bottom:0; } </style> </head> <body> <div...

Syntax error in Insert query in Mysql in VB.Net

mysql,vb.net

you miss the closing parenthesis for the values list: Dim cmd1 As New OdbcCommand("insert into party values('" + pcode_txt.Text + "','" + Trim(UCase(name_txt.Text)) + "','" + Trim(UCase(addr_txt.Text)) + "','" + phone_txt.Text + "','" + combo_route.SelectedItem + "','" + combo_area.SelectedItem + "')", con) My answer is perfectly fit to your question...

check if a list contains all the element in an array using linq

vb.net,linq

You can use Enumerable.All: dim linqMeddata = From m In medicineDataList Where keys.All(Function(k) m.MedicineData.Contains(k)) Order By m.MedicineName Ascending Select m ...

Custom drawing using System.Windows.Forms.BorderStyle?

c#,.net,vb.net,winforms,custom-controls

If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

Convert date to string format

vb.net,converter

Your approach doesn't work because you are using ToString on a DataColumn which has no such overload like DateTime. That doesn't work anyway. The only way with the DataTable was if you'd add another string-column with the appropriate format in each row. You should instead use the DataGridViewColumn's DefaultCellStyle: InvestorGridView.Columns(1).DefaultCellStyle.Format...

Can't output Guid Hashcode

sql,vb.net,guid,hashcode

Well, are you looking for a hashcode like this? "OZVV5TpP4U6wJthaCORZEQ" Then this answer might be useful: Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=",""); GuidString = GuidString.Replace("+",""); Extracted from here. On the linked post there are many other useful answers. Please take a look! Other useful links:...

Select @field From table as parameter

asp.net,sql-server,parameter-passing

If doing it from codebehind works then you can do something like sdsOrderErrors.SelectCommand = string.Format("SELECT {0} AS fld FROM [a_table]", colName); (OR) Have a stored procedure to accept a parameter and perform a dynamic query to achieve the same like create procedure usp_testSelect(@colname varchar(30)) as begin declare @sql varchar(200); set...

Comparing arrays with numbers in vb.net

arrays,vb.net

There are a few basic ways of checking for a value in an integer array. The first is to manually search by looping through each value in the array, which may be what you want if you need to do complicated comparisons. Second is the .Contains() method. It is simpler...

Third-party security providers like Google, Twitter etc. in ASP.Net

asp.net,authentication

No, you cannot enter any string. You will need to register with each provider to get the parameters that you need. See http://www.asp.net/web-api/overview/security/external-authentication-services for instructions on how to do this....