Tag Archives: Technology

Nuget package listing fails on the machine behind corporate firewall

I was unable to browse packages from visual studio, Package Manager Console or GUI. The message would be no packages found in the current source. Using Fiddler, I am opted to watch the traffic being sent, and all HTTP requests are successfully made and completed. When searching for “Log” I get a single request for the count of items (45), and then the follow up filter request with all 45 package items in detail. To verify if something within our corporate network was blocking the request, I also made each of the requests from Internet Explorer, and both were successful.

I realised that the response type is different and seems our corporate firewall policy is blocking them. I browsed for the solution and I found the it in Nuget Issue tracker which is helpful:
You can get around it with Fiddler2 and FiddlerScript. Edit the FiddlerScript, find the method “OnPeekAtResponseHeaders” and add the following code fragment before the method closing brace.


  if (oSession.HostnameIs("packages.nuget.org") && oSession.oResponse["Content-type"].Contains("text/xml")) {
        oSession.oResponse["Content-type"] = oSession.oResponse["Content-type"].Replace("text/xml", "application/atom+xml");
    }

This will modify the response type. Thank you Nuget guys…

CLR Profiler – message “Waiting for application to start common languange runtime”

Sometimes you may get this message when you start CLR profiler, this means that you don’t have enough permissions to run clr profiler or wrong clr version selected

You can start the clr profiler as “Run as Administrator” if that could solve then fine else check the proper clr version mostly for silverlight applications use “Core CLR version”.

Most of the microsoft products run the 32-bit so try using 32 bit binaries.

Dynamic in VB.Net and Creating a wrapper

I was trying some new things and its not that difficult to implement Dynamic Object in VB.Net either. I tried by creating a dynamic class which can take any number of fields by using a dictionary object

Initially i created SomeDictionary Class

Public Class SomeDictionary
Private ReadOnly _values As Dictionary(Of String, Object)
Private ReadOnly _oldValues As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()

Public Sub New()
_values = New Dictionary(Of String, Object)
End Sub

Public Sub New(values As IDictionary(Of String, Object))
_values = values
End Sub

Default Public Property SomeDictionary(key As String) As Object
Get
Dim result As Object = Nothing
_values.TryGetValue(key, result)
Return result
End Get
Set(value As Object)
If Not _oldValues.ContainsKey(key) Then
Dim oldValue As Object = Nothing
_values.TryGetValue(key, oldValue)
_oldValues(key) = oldValue
End If
_values(key) = value
End Set
End Property

Public Function GetChanges() As IDictionary(Of String, Object)
Dim result = (From key In _oldValues.Keys
Let oldValue = _oldValues(key)
Let newValue = _values(key)
Where Not Object.Equals(oldValue, newValue)
Select New With {.Key = key, .Value = newValue}).ToDictionary(Function(p) p.Key, Function(p) p.Value)
Return result
End Function

End Class

Once this is done, I created a sample Dynamic class

Public Class SomeCommonClass
Inherits Dynamic.DynamicObject
Dim _tracking As SomeDictionary
Public Sub New()
_tracking = New SomeDictionary()
End Sub
Public Overrides Function TrySetMember(binder As Dynamic.SetMemberBinder, value As Object) As Boolean
Try
If _tracking Is Nothing Then
Return False
End If
_tracking(binder.Name) = value
Catch ex As Exception

End Try
Return True
End Function

Public Overrides Function TryGetMember(binder As Dynamic.GetMemberBinder, ByRef result As Object) As Boolean
Try
If _tracking Is Nothing Then
Return False
End If
If _tracking(binder.Name) Is Nothing Then
result = Nothing
Return False
End If
result = _tracking(binder.Name)
Catch ex As Exception

End Try
Return True
End Function

Public Overrides Function TryInvokeMember(binder As Dynamic.InvokeMemberBinder, args() As Object, ByRef result As Object) As Boolean
Try

Dim mInfo = GetType(SomeDictionary).GetMethod(binder.Name)
If mInfo Is Nothing Then
result = Nothing
Return False
Else
result = mInfo.Invoke(_tracking, args)
End If
Return True
Catch ex As Exception
result = Nothing
Return False
End Try
End Function
End Class

We can override the setmember and getmember methods of DynamicObject class and use it the way we like it.
We can also override the InvokeMember method also so that we can implement the kind of response we want when the user calls a method. Here just for example I used the same Dictionary class to implement this method we can use any other method also in case if you are creating a dyanamic class as a wrapper:
Calling the Dynamic class is also very simple

Dim some As Object = New SomeCommonClass
some.Name = "Kishore Patil"
some.Phone = "12124455"
some.Address_City = "Cincinnati"
some.Address_Street = "8000 Some Dr"
some.Address_State = "Ohio"

We can use this particular class to have any kind of field stored and retrived using the Dictionary.
The following is the example converted to VB.Net originally published here for C#

Public Class DynamicXmlNode
    Inherits Dynamic.DynamicObject
    Dim node As XElement

    Public Sub New(node As XElement)
        Me.node = node
    End Sub

    Public Sub New()

    End Sub

    Public Sub New(name As String)
        node = New XElement(name)
    End Sub
    Public Overrides Function TryConvert(binder As Dynamic.ConvertBinder, ByRef result As Object) As Boolean

        If binder.Type = GetType(String) AndAlso binder.ReturnType = GetType(String) Then
            result = node.Value
            Return True
        ElseIf binder.Type = GetType(Integer) AndAlso binder.ReturnType = GetType(Integer) Then
            result = node.Value
            Return True
        End If
        Return True
    End Function

    Public Overrides Function TrySetMember(binder As Dynamic.SetMemberBinder, value As Object) As Boolean
        Dim setNode As XElement = node.Element(binder.Name)
        If Not setNode Is Nothing Then
            setNode.SetValue(value)
        Else
            If value.GetType = GetType(DynamicXmlNode) Then
                node.Add(New XElement(binder.Name))
            Else
                node.Add(New XElement(binder.Name, value))
            End If

        End If
            Return True
    End Function

    Public Overrides Function TryGetMember(binder As Dynamic.GetMemberBinder, ByRef result As Object) As Boolean
        Dim getNode As XElement = node.Element(binder.Name)
        If Not getNode Is Nothing Then
            If getNode.HasElements Or String.IsNullOrEmpty(getNode.Value) Then
                result = New DynamicXmlNode(getNode)
            Else
                result = getNode.Value
            End If

            Return True
        Else
            result = Nothing
            Return False
        End If
    End Function

    Public Overrides Function TryInvokeMember(binder As Dynamic.InvokeMemberBinder, args() As Object, ByRef result As Object) As Boolean
        Try
            Dim xmlType As Type = GetType(XElement)
            result = xmlType.InvokeMember(binder.Name, Reflection.BindingFlags.InvokeMethod Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance, Nothing, result, args)
            Return True
        Catch ex As Exception
            result = Nothing
            Return False
        End Try

    End Function
End Class

To use Convert in VB we need to something like this CTypeDynamic(node.Address.City, GetType(String)). It’s very helpful in writing wrappers only drawback being its slow and no intellisense will be available.

ORA-12154: TNS:could not resolve the connect identifier specified

Recently when my machine was reimaged all my previous settings were lost. I had real hard time setting up the connection with oracle server from my machine. I installed ODT with ODAC from oracle but something was missing which resulted in “ORA-12154: TNS:could not resolve the connect identifier specified” error message. After reading several blogs I came to know that I have to set the server, host and port details in tnsname.ora file
# alias =
# (DESCRIPTION =
# (ADDRESS = (PROTOCOL = TCP)(HOST = myserver.mycompany.com)(PORT = 1521))
# (CONNECT_DATA =
# (SERVER = DEDICATED)
# (SERVICE_NAME = orcl)
# )
# )

I updated the Host and service name but still something was missing which resulted in the same above error message. After some trial and error methods I was finally able to solve this issue. In the application they were using alias name as datasource in the connection string where as I gave some dummy alias name.
When I finally gave the correct alias name in the tnsname.ora and in the connection string datasource the issue was fixed.

Hope this saves someone’s time.

Converting DataSet to JSon

When you can create RESTful webservices using WCF and send response in JSon format. Mostly we faced issues converting Dataset/Datatable to JSon string, the following code is simple and most of them may know about this but just for those who are in a hurry . This is written in VB, mostly you find some help for C# but not for VB and also note this works well with .Net 3.5/4.0

You can create your own (custom) dataset



Public Class MyDataSet
	Inherits System.Data.DataSet

	Public Sub New()
	End Sub

	Public Function toJSon() As String
		Dim response As String = “”
		Try
			If (Me.Tables.Count > 0) Then
				Dim serialize As JavaScriptSerializer = New JavaScriptSerializer()
				response = serialize.Serialize(ToDictionary(Me))
			End If
		Catch ex As Exception
		End Try
		Return response
	End Function

	Private Function toTableDictionary(ByVal data As DataTable) As Object
		Dim dic As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
		dic.Add(data.TableName, toRowDictionary(data))
		Return dic
	End Function

	Private Function toRowDictionary(ByVal data As DataTable) As Object
		Dim col = data.Columns.Cast(Of DataColumn)().ToArray
		Return data.Rows.Cast(Of DataRow)().Select(Function(r)col.ToDictionary(Function(c) c.ColumnName, Function(c) r(c)))
	End Function

	Private Function ToDictionary(ByVal data As DataSet) As Dictionary(Of String, Object)
		Return data.Tables.Cast(Of DataTable)().ToDictionary(Function(t)t.TableName, Function(t) toRowDictionary(t))
	End Function

End Class

you can use this dataset and call the .toJson just as you call .toString()

Hope this helps someone in need…

CSS for Disabled anchor tag on asp.net

In the asp.net when the link was disabled it used to apply the disabled properties for the anchor tags. With the 4.0 .Net framework, the colors won’t apply automatically. They introduced a new property for all controls DisabledCssClass which is a string property to set/get the disabled css class. This property is applied to all the controls.
This property can be used to change the name that is rendered for the DisabledCssClass property of individual Web controls. By default, this property returns “aspNetDisabled“.
When SupportsDisabledAttribute is overridden in a derived class to return false, the value of the DisabledCssClass property is rendered as the value of the class attribute of the HTML element for the control. In that case, if there is a value in the CssClass property, both CSS classes will be applied to the rendered HTML element. The class attribute will consist of the value of the DisabledCssClass property followed by the value of the CssClass property, separated by a space.
This property is static, which means that you can set it only for the WebControl class. Whatever value you set it to is used for all controls in a Web application. You cannot specify different values for individual controls.
If you want to set a new class for all the controls all over the application, you can set a new class in the application_start event in global.asax

void Application_Start(object sender, EventArgs e)
{
webcontrol.DisabledCssClass = somecssclass;
}

If you want to set the DisabledCssClass for an anchor tag, you can do that in the stylesheet like

a.aspNetDisabled
{
color:000FFF#;
}

This set of property is applied to anchor tag without affecting any other controls.

IIS SEO Toolkit to create Robots.txt and Sitemap.xml

With the IIS7 SEO Toolkit one can manage Robots.txt to allow/disallow rules for your web application. To use this tool, type INETMGR in the start command to open IIS Management console, navigate to your website using the treeview on the left side. Select the SEO Toolkit in the management console:
You will find Site Analysis, Sitemaps and sitemap indexes and Robots Exclusion. You can perform site analysis on your website to analyze your website.

Robot Exclusion protocol under SEO Toolkit uses ‘Allow/Disallow’ rules to inform search engines about the URL paths that can be crawled and that to be ignored. One can set the rules for anyone specific user agent or for all user agents using user agent HTTP header.

To create or update the existing Robots.txt file, select the appropriate link under Robots Exlusion based on your requirement to Add a new Allow rules or to Add a new Disallow rules or view existing rules. If you have selected to Add a new DisAllow rule a new Add Disallow rule dialog is opened. Select the User agent you are targeting In the URL structure, yu can select the physical location or previously performed Site Analysis or you can run a new IIS Site Analysis. Based upon your selections, URL are displayed under URL path. Select the URLs that you want to apply rules. Press ‘OK’ to confirm the changes. The Robots.txt file will be updated ( or creates a new Robots.txt if does not exist).

Use sitemaps to inform the search engines the locations that are available for indexing. You can create Sitemaps using SEO toolkit. Select ‘Create new Sitemap’ under the Sitemap and Sitemap Index, give a name to the sitemap(like sitemap.xml) in the New Sitemap dialog. Upon creating it opens a dialog to add URLs to the site map. Set the domain name, URL structure to select the URL’s under the URL path treeview.

Upon creation of sitemap you can add the sitemap.xml to the Robots.txt file by selecting Add to the Robots.txt.

Access .Net webservices which return complex types

I thought it was pretty simple for a beginner like me to parse the dataset returned from .Net webservices. I tried all the options, tried to map like
envelope.addMapping(“Namespace”, “class or tag”, classname);
but this one works fine with the complex types not with the datasets. Or maybe I might have missed something, I was not able to parse data.

For simple types we can use this

private SoapObject table = null;       // Its the table of a DataSet
private SoapObject client = null;       // Its the client pettition to the web service
private SoapObject tableRow = null;      // Gets the information of a row from the table DataSet
private SoapObject responseBody = null;     // Its the whole response of the WebService
private HttpTransport transport = null;     // Its whta is used to make the call to the WebService
private SoapSerializationEnvelope sse = null;
sse = new SoapSerializationEnvelope(SoapEnvelope.VER11); // SOAP version is indicated here. Version 11 works nice
sse.addMapping(<webService NameSpace>, <name of the Class using it>, this.getClass());
sse.dotNet = true; // We stablish we sill be working with .NET webservices
transport = new HttpTransport(<url of the webservices>);
transport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); transporte.debug = debug; // Set it to either use transport.requestdump or reponsedump to see the xml of the webservice request or response
// Here we set who are we gonna call, give the method arguments and do the call
client = new SoapObject(<webServiceNameSpace>, <webService Method Name we want to reuqest>);
// You can add as many properties as many as you need. I'd say that you set your webservices method to recieve only strings and do the convertions on you webservice. Its quite hard work with primitive values
client.addProperty(<agument name as String>, <argument Value>);
sse.setOutputSoapObject(client);
sse.bodyOut = client;
transporte.call(<webService direct url>, sse);
// We'll get the whole XML reponse with all the information
responseBody = (SoapObject) sse.getResponse();
// Now, the reponse works as a Vector. On position 0 we have the information of the Reponse while in position 1 we get the info we requested. So we get rid of the information reponse and lets grab the info we requested
responseBody = (SoapObject) responseBody.getProperty(1);
// And now, we have the n tables the WebService returned to us with the information, but still we can't access the info, so we'll get one of the tables separated. We'll use a very different variable for not to lose the whole info the webservice sended us. Once again, the tables are contained on a Vector. Lets grab the first one
table = (SoapObject) responseBody.getProperty(0);
// Now we have the table, but still can't use the info, soooo, lets grab a row individually
tableRow = (SoapObject) table.getProperty(0);

tableRow.getProperty(<columnName>).toString()

sse.getResponse()

It worked pretty fine when we have few records.

I parsed the responsedump xml to parse the response data into objects using SAXParser. I felt this one to be easy way.

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
XMLReader reader = parser.getXMLReader();
//Use the handler to parse the XML
ExampleHandler handler = new ExampleHandler();
reader.setContentHandler(handler);
reader.parse(new InputSource(new ByteArrayInputStream(transport.responsedump.getbytes())));
Object object = handler.parsedata();

The response can be captured from handler. You need to create a handler with the parsedata.

Hope this helps..

Consuming webservice from Android

I was trying to consume .Net webservices from Android application using ksoap2-for-android sdk, I was getting proper response when there are no parameters to pass. When I’m trying to pass parameters, I was not succeeded. I seached lots of forums, there are so many suggestions, after implementing them I was able to send parameters and get the response correctly.

This was my code:

private static final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private static final String METHOD_NAME = "CelsiusToFahrenheit";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String strURL = "http://w3schools.com/webservices/tempconvert.asmx";
TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv =(TextView)findViewById(R.id.TextView01);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Celsius","23.5");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.encodingStyle=SoapSerializationEnvelope.ENC;
envelope.setOutputSoapObject(request);
AndroidHttpTransport transport ;
try
{
transport = new AndroidHttpTransport(strURL);
transport.debug=true;
transport.setXmlVersionTag(/"<?xml version=/"1.0/" encoding=/"utf-8/"?/>");
transport.call(SOAP_ACTION, envelope);
SoapPrimitive resultString = (SoapPrimitive)envelope.getResponse();
tv.setText("Status:" + resultString.toString());
catch(Exception e){
e.printStackTrace();
}
}

To resolve the issue regarding Outbound parameters passed as null, the following suggestions were been provided:

1. If you are using IE set to Access data across domains to enabled
2. change addProperty(“Temperature”,”23.5″); to addProperty(“arg0″,”23.5”); even without implementing this suggestion also I was able to connect
3. Set the encoding style for the envelope.
4. Set the boolean dotnet if you are connecting .Net web service
5. There is also a workaround to use ksoap and java.net tools combined to connect to webservice with the entire soap body specified.
6. Set the Content-Type
7. And if you are connecting a webservice on your localmachine, then provide the ipaddress rather than localhost/webservicename like 198.10.129.2/webservicename
8. Sometimes UAC blocks the connection, try running eclipse in administrator mode.

These are the suggestions kept together any of them may work for you..

Hope this saves someone’s day

Page is accessing information that is not under its control while accessing a webservice

When I created a html page which consumes a webservice which is on some other domain, I used to get the prompt box on ie7 which says “Page is accessing information that is not under its control. This poses a security risk. Do you want to continue” with yes/no buttons. When I click yes, it works fine but when I click no it said Permission denied. I wanted to suppress this error.
It’s far from a perfect system, but it’s simple. Since there is no way to specify which pages trust other pages to access their data, Internet Explorer simply says that if two pages are not in the same domain, they cannot communicate. More precisely, Zone Manager (found on the security tab in Internet Settings) does allow the user to say that a page may access another page, but as you point out, most people leave it set on prompt.
You can suppress it getting into Internet Options -> Security Tab select internet and click custom actions button, in the pop up enable “Access data sources across domains” which is in the miscellaneous section.
You can suggest users add the page to the trusted site zone, or merely say Yes to the dialog box. Cross-domain security issues can be quite serious. Whenever you access data sources that are in a different context than your script, there are potential problems. A solution here would be to create a safe ActiveX® control that will perform the tasks you need and lock it down to the intranet site or creating a webservice in your local domain and accessing the webservice from different domain from your webservice. You can use your webservice in your application.