Wednesday 3 August 2011

Validation: black or white list

When you’re validating data – either client- or serverside – there are basically two strategies you can choose between. You can either blacklist data or white list data. Blacklisting seems to be the most popular way to validate data, but white listing is so much better. Here’s a brief description of the two strategies and why the white listing is better.

The black listing strategy is validating you input against a list of characters which are illegal in the input. You can either reject input containing the blacklisted characters or just remove them from the input.
The white listing strategy is just about the opposite. You have a list of allowed characters, and any character, which isn’t in the list is rejected or removed.
Suppose the user has to input a phonenumber. It may look in a number of different ways:
80808080
8080-8080
80-80-80-80
80 80 80 80
+45 8080 8080
So when white listing we’re allowing numbers and just numbers.
When blacklisting we’re disallowing letters, spaces and special characters.
Suppose we want to allow international numbers – which is often written with a plus sign to signify the international access code.
Altering the white list is quite simple – we add the plus character to the allowed list of characters.
Altering the black list is a mess. We alter “no-special characters” to allow the plus character but not any other special characters – but do you know them all?
In white listing you know what you allow to pass thorugh, but do you know what you’ve forgotten, when you black list?

Tuesday 5 July 2011

Setting the Value of a TextBox with TextMode=Password

 

 

When the TextMode property of an ASP.NET TextBox is set to Password the value set in the Text property will not display at runtime. This can be a pain, however it is actually by design to prevent the unmasked password from being displayed in the HTML source of the page.

While the security reasons are good to not display the masked password value, leaving it unmasked in the source, it is also necessary at times to display the masked value in the TextBox. For example, a user profile page where the user has the ability to change their password. It makes sense to display it there. After all, the user has already authenticated to get to the page (although the value is sent with the data to the browser and could easily be sniffed).

Security reasons aside, you can work around this by adding the password value to the control as as Attribute. Since the TextBox renders as an HTML input control, you can set the value attribute easily, just as you would set the Text property.

PasswordText.Attributes.Add("value", "ThePassword");
Use this to set the value, instead of setting the Text property. You can still read the value from the control via the Text property.

Tuesday 28 June 2011

Important Points to remember

 

 

  1. Microsoft Outlook : Shift+F3 will change the upper case to lower , lower to upper or makes 1st letter Upper case.

Tuesday 12 April 2011

Microsoft.Jet.OLEDB.4.0 provider is not registered on the local machine

 

image

 

Recently I deployed an aspx web application that is running OK on a 64 bit Windows 7 system. The web page would open Ok but trying to run a part of application that would read a csv/Excel file and parse it, using win forms application I am getting the above error message.

The fix involved two things:

1. Rebuilding the application specifically for 32 bit system. To do this for a VB.NET project, open project properities, select Compile tab, click on ‘Advanced Settings’ then select x86 for the system (not "Any CPU").
or
In case of Web project

2. On IIS system on the server, on the application pool for this application, select properties and then tick on "Enable 32 bit applications".

 

 

image

Saturday 2 April 2011

Converting hex to varbinary and vice versa

 

HexString To Varbinary :

CREATE FUNCTION [dbo].[fnHexStrToVarbinary]
(
@inputText varchar(max)
)
returns varbinary(max)
as
begin

declare @binvalue varbinary(8000), @sqlstring Nvarchar(1000)

--X Query

select @binvalue = cast('' as xml).value('xs:hexBinary( substring(sql:variable("@inputText"), sql:column("t.pos")) )', 'varbinary(max)')
from (select case substring(@inputText, 1, 2) when '0x' then 3 else 0 end) as t(pos)

RETURN @binvalue

end

Testing :


declare @hexstring varchar(MAX)
select @hexstring = ‘0x001be96ccd14ef47acbf24583b972c250100000031071af34c3e9aac1346d62c8507f0ab9255c827adcf82fad7029c1ee844fcfd1d3b89cf6e89afcda812441be1c9a5b5’

select dbo.[fnHexStrToVarbinary](@hexstring)

 

Varbinary to Hex string :

declare @binary varbinary(MAX)
select @binary = 0x001be96ccd14ef47acbf24583b972c250100000031071af34c3e9aac1346d62c8507f0ab9255c827adcf82fad7029c1ee844fcfd1d3b89cf6e89afcda812441be1c9a5b5

select master.dbo.fn_varbintohexstr(binary) --Built in function

So altogether we can convert one from another like this..


declare @hexstring varchar(MAX)

declare @binary varbinary(MAX)
select @binary = 0x001BE96CCD14EF47ACBF24583B972C250100000031071AF34C3E9AAC1346D62C8507F0AB9255C827ADCF82FAD7029C1EE844FCFD1D3B89CF6E89AFCDA812441BE1C9A5B5 – must not include in ‘’ as it is a varbinary field.

select  @hexstring = master.dbo.fn_varbintohexstr(@binary)

print @hexstring
select dbo.[fnHexStrToVarbinary](@hexstring)

select case when dbo.[fnHexStrToVarbinary](@hexstring) = @binary then ‘Same Values’ else ‘Different Values’
end

Thursday 31 March 2011

Enable multiple site bindings in WCF 4.0

 

When trying to access my WCF hosted in IIS7..I am getting this error.

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection.
Parameter name: item

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection.
Parameter name: item
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. 
Parameter name: item]
   System.ServiceModel.UriSchemeKeyedCollection.InsertItem(Int32 index, Uri item) +15583484
   System.Collections.Generic.SynchronizedCollection`1.Add(T item) +65
   System.ServiceModel.UriSchemeKeyedCollection..ctor(Uri[] addresses) +62
   System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +266
   System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +42
   System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +427
   System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +604
   System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +46
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +654
 
[ServiceActivationException: The service '/MBPublicScheme/Default.svc' cannot be activated due to an exception during compilation.  The exception message is: This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection. 
Parameter name: item.]
   System.ServiceModel.AsyncResult.End(IAsyncResult result) +15700960
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +15623609
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +265
   System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +227
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
 
 
I have gone through so many sites and did tried all the possible solutions like :
 
 With ASP.NET 4.0, add the following lines to your web.config: 




        <system.serviceModel> 
             <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
        </system.serviceModel> 


        With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:

        <system.serviceModel> 
             <serviceHostingEnvironment> 
                  <baseAddressPrefixFilters> 
                       <add prefix="httplinktoyoursite"/
                  </baseAddressPrefixFilters> 
             </serviceHostingEnvironment> 
        </system.serviceModel> 

         

They may working in different scenarios but in my case i have to remove the one of the bindings in IIS.

clip_image002[4]


 


 


clip_image002[6]


Remove the binding with IPAddress.

Friday 18 March 2011

Remove Decimal Places From Currency Format

 

Solution 1 :

Use the following format in String.Format({0:c} , amount)

{0:c} default

{0:c0} for no decimal

{0:c3}for 3 decimal places and so on.

add 1,2,3 any number after c for that many decimal places

 

Solution 2 :

Dim nfi As New System.Globalization.NumberFormatInfo

nfi.CurrencyDecimalDigits = 0
nfi.CurrencySymbol = "£"

Dim amount As String = "300.440000000000"
Me.Label_Amount.Text = String.Format(nfi, "{0:c}", amount)

 

To Use the current culture instead of creating new one use this.

Dim nfi = DirectCast(System.Globalization.NumberFormatInfo.CurrentInfo.Clone(), System.Globalization.NumberFormatInfo)

nfi.CurrencyDecimalDigits = 0     

Dim amount As String = "300.440000000000"
Me.Label_Amount.Text = String.Format(nfi, "{0:c}", amount)

Thursday 10 March 2011

VB Date Format

VB uses two different date locales - the system locale that determines the output format of the date, and the code locale, which is ALWAYS U.S. English. Using the "#" delimiter (as recommended by MSDN) forces the date to be interpreted as the code locale - U.S. English, and thus mm/dd/yyyy; the system locale has no influence on this.

However, VB tries to be helpful when interpreting an entered date, and this can cause no end of trouble and confusion. For example:

    #18/04/2002# is interpreted as 18th April 2002

    #04/18/2002# is also interpreted as 18th April 2002

    #08/04/2002# is interpreted as 4th August 2002

It seems that the date is taken as mm/dd/yyyy when it makes sense, otherwise VB assumes that it's dd/mm/yyyy, and does it's own format conversion behind the scenes. This problem is compounded when dates are passed to SQL Server as part of an embedded SQL statement.

It is far, far better to ignore the MSDN advice, and pass dates as SQL character strings, always pre-formatted to the desired date format. For example:

"Where startdate > '" & format$(Now, "mm/dd/yyyy") & "' "


Note that the date string MUST be enclosed in single quotes, as above.


This can still cause problems, though, depending on the date format that your particular SQL Server installation is expecting. One solution is to include a "SET DATEFORMAT mdy" statement at the start of the Select statement. A better solution is to always format the date in a way that is not open to misinterpretation by SQL Server; dates such as 2002-08-04 and 04 Aug 2002 seem to be translated OK irrespective of the date format settings in either VB or SQL Server.



So, the above "Where" statement could be coded as either:



"Where startdate > '" & format$(Now, "yyyy-mm-dd") & "' "


or



"Where startdate > '" & format$(Now, "dd mmm yyyy") & "' "


Both of these will work as expected.



As an aside, I don't think that it's a good idea to use "short date" and "long date" as part of a format$ function, where the formatted dates are being used as part of a SQL statement, as these formats can be defined differently on different machines. Thus, a piece of code might work fine on machine A, but either crashes or produces incorrect results on machine B.



 http://www.vb-helper.com/bug_sql_dates.html



 My Problem:



I have one stored procedure and one view.




View :



“SELECT * FROM [dbo].[vwOutstandingHBVBSInstructions] WHERE [Instruction Received] >= '" & Format$(txtFromDate.Value, "mm/dd/yyyy") & "'" & " AND [Instruction Received] <= '" & Format$(txtToDate.Value, "mm/dd/yyyy") & "'"



Its working fine without any problem.



If I use the same date format mm/dd/yyyy while passing date parameters to stored procedures it is changing the format to dd/mm/yyyy(Initially i am very confused and couldn’t figure out the problem until i used SQlProfile to test the parameters it is passing to the stored procedure and view).



    Dim comm As New ADODB.Command

    comm.ActiveConnection = conn


    comm.CommandText = "spMyProc"


    comm.CommandType = adCmdStoredProc


    comm.Parameters.Append comm.CreateParameter("@FromDate", adDBDate, adParamInput, 100, Format$(txtFromDate.Value, "mm/dd/yyyy"))


    comm.Parameters.Append comm.CreateParameter("@ToDate", adDBDate, adParamInput, 100, Format$(txtToDate.Value, "mm/dd/yyyy"))


    Set objRS = comm.Execute



this format is giving error.



So i have to changed it to ‘dd/mm/yyyy’

Monday 31 January 2011

Send Mail Using MS Access Forms and VB6

 

Use DoCmd.SendObject

The SendObject method carries out the SendObject action in Visual Basic.
DoCmd.SendObject(ObjectType, ObjectName, OutputFormat, To, Cc, Bcc, Subject, MessageText, EditMessage, TemplateFile)

ObjectType - Optional AcSendObjectType.
AcSendObjectType - Can be one of these constants.

acSendDataAccessPage
acSendForm
acSendModule
acSendNoObject default
acSendQuery
acSendReport
acSendTable

ObjectName - An optional string variant expression that's the valid name of an object of the type selected by the objecttype argument.

New! Download Access example of the Sendobject Method

If you want to include the active object in the Email message, specify the object's type with the objecttype argument and leave this argument blank. If you leave both the objecttype and objectname arguments blank (the default constant, acSendNoObject, is assumed for the objecttype argument), Microsoft Access sends a message to the Email application without an included database object. If you run Visual Basic code containing the SendObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
OutputFormat - Optional Variant.
To - An optional string expression that lists the recipients whose names you want to put on the To line in the E-mail message. Separate the recipient names you specify in this argument and in the cc and bcc arguments with a semicolon (;) or with the list separator set on the Number tab of the Regional Settings Properties dialog box in Windows Control Panel. If the recipient names aren't recognized by the Email application, the message isn't sent and an error occurs. If you leave this argument blank, Microsoft Access prompts you for the recipients.
Cc - An optional string expression that lists the recipients whose names you want to put on the Cc line in the mail message. If you leave this argument blank, the Cc line in the mail message is blank.
Bcc - An optional string expression that lists the recipients whose names you want to put on the Bcc line in the mail message. If you leave this argument blank, the Bcc line in the mail message is blank.
Subject - An optional string expression containing the text you want to put on the Subject line in the mail message. If you leave this argument blank, the Subject line in the mail message is blank.
MessageText - An optional string expression containing the text you want to include in the body of the mail message, after the object. If you leave this argument blank, the object is all that's included in the body of the mail message.
EditMessage - Optional  - use True (–1) to open the electronic mail application immediately with the message loaded, so the message can be edited. Use False (0) to send the message without editing it. If you leave this argument blank, the default (True) is assumed.
TemplateFile - Optional string expression that's the full name, including the path, of the file you want to use as a template for an HTML file.

 

 

Ex:

DoCmd.SendObject acSendReport , "Sales By Order", acFormatRTF , "To@gmail.com", "Cc@gmail.com", "Bcc@gmail.com","Subject", "Message", False   

The SendObject method provides a way to send a MAPI mail message programmatically in Microsoft Access. However, the SendObject method does not give you access to complete mail functionality, such as the ability to attach an external file or set message importance. The example that follows uses Automation to create and send a mail message that you can use to take advantage of many features in Microsoft Outlook that are not available with the SendObject method.

 

Use Oulook

Add a reference to the vb project:

  1. On the Tools menu, click References.
  2. In the References box, click the Microsoft Outlook 10.0 Object Model and then click OK.

Private Sub UsingOutLook()
    Dim objOutlook As Outlook.Application
    Dim objEmail As Outlook.MailItem
    '***creates an instance of Outlook
    Set objOutlook = CreateObject("Outlook.Application")
    Set objEmail = objOutlook.CreateItem(olMailItem)
    Dim toEmail As String
    Dim Content As String
    Content = "Hi, How Are You?"
    toEmail = "lakshmidupati@utdgroup.com"
    '***creates and sends email
    With objEmail
        .To = toEmail
        .subject = "Mail From MS Access"
        ‘.Body = “Anything” 
‘Use this if body doesnt contain any html tags.
        .BodyFormat = olFormatHTML
        .HTMLBody = "<html><br/>Hi<br/>Your Message</html>"
        .Send
'sends the email in Outlook.  Change to DISPLAY if you want to be able to
                      'modify or see what you have created before sending the email
    End With
    '**closes outlook
    objOutlook.Quit
    Set objEmail = Nothing
End Sub

 

 

Use SMTP

 

Dim myMail As New MailMessage()
myMail.From = "from@gmail.com"
myMail.To = "to@gmail.com"
myMail.Subject = "SMTP Mail"
myMail.Priority = MailPriority.Low
myMail.BodyFormat = MailFormat.Html
myMail.Body = "<html><body>SMTP Mail- success</body></html>"
Dim myAttachment As New MailAttachment("c:\attach\attach1.txt", MailEncoding.Base64)
myMail.Attachments.Add(myAttachment)
SmtpMail.SmtpServer = "MyMailServer"
SmtpMail.Send(myMail)


Friday 14 January 2011

WCF Errors

 

Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException: Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.
Source Error:

Line 6:          Dim obj As New PublicSchemeLibrary.SchemeClass()
Line 7: Dim currdate As DateTime = DateTime.Now
Line 8: Response.Write("<HTML><HEAD></HEAD><BODY>" + obj.GetSchemes() + "</BODY></HTML>")
Line 9: Response.Write(ControlChars.NewLine)
Line 10: Response.Write(Environment.NewLine)


Source File: c:\inetpub\wwwroot\UI\Schemes.aspx.vb    Line: 8


Stack Trace:





[SerializationException: Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. ]
System.Runtime.Serialization.XmlObjectSerializerContext.IncrementItemCount(Int32 count) +199
ReadMBPublicSchemeSummaryFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] ) +630
System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) +83
System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) +39
System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) +1730
System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns) +74
ReadArrayOfMBPublicSchemeSummaryFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract ) +214
System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) +220
System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) +39
System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, DataContract& dataContract) +1730
System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns) +66
System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName) +1042
System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName) +416
System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName) +66
System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest) +152

[NetDispatcherFaultException: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:objSchemes. The InnerException message was 'Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. '. Please see InnerException for more details.]
PublicSchemeLibrary.SchemeClass.GetSchemes() in C:\Documents and Settings\lakshmidupati\My Documents\Visual Studio 2005\Projects\UI\PublicSchemeLibrary\SchemeClass.vb:285
Schemes.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\UI\Schemes.aspx.vb:8
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2603


 



Solution :



http://www.devx.com/dotnet/Article/38407/1763/page/2



4. Change the max buffer size and max received message size (if needed).


At run time you may encounter two errors related to the amount of data being served by the server:




  1. The maximum message size quota for incoming messages (65536) has been exceeded.


  2. Maximum number of items that can be serialized or deserialized in an object graph is '65536'.



WCF limits the amount of data you can send over the wire per call to 64K, which is why the first error occurs. If your endpoint has methods that return more data than that (such as a collection), you have to change the buffer size and max received size from 64K to a suitable number.



If you add a service by using the add service reference option, the values added on the server won't always reflect on the client. The client always defaults to 64K, which can cause a lot of confusion if many developers are changing the client configuration. A binding value that is updated on the server will have to be changed again on the client.



To fix the second error mentioned above, you can add the following element to the client config file in the service behavior section (2147483647 is used as an example only):



 


<dataContractSerializer maxItemsInObjectGraph="2147483647" /> 


 



 



Fisrt we must add a section to our app.config servicemodel  : endpoint behavior:




    <behaviors>

      <endpointBehaviors>


        <behavior name="Graph">


          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>


        </behavior>


      </endpointBehaviors>


    </behaviors>




Then at your endpoint you can reference it:



<client>



<endpoint address=http://DomainName/PublicScheme/default.svc


          binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IPublicScheme"


          contract="WCF_PublicScheme.IPublicScheme" name="BasicHttpBinding_IPublicScheme" behaviorConfiguration="Graph"/>


    </client>



It should solve the problem.

Tuesday 11 January 2011

Useful Commands from Command Prompt :

 

To Flush/Refresh the Cache

Z:\>ipconfig /flushdns

Windows IP Configuration

Successfully flushed the DNS Resolver Cache.

Z:\>ipconfig /flushdns

 

SVCUTIL to get metadata of a service

C:\Program Files\Microsoft Visual Studio 8\VC>svcutil /t:metadata http://utdws109/MBPublicScheme/default.svc?wsdl

Cannot obtain Metadata from http://IPAddress/Service/default.svc?wsdl ----DNS Settings

C:\Program Files\Microsoft Visual Studio 8\VC>svcutil /t:metadata http://192.168.1.51/MBPublicScheme/default.svc?wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.30]
Copyright (c) Microsoft Corporation. All rights reserved.

Attempting to download metadata from 'http://192.168.1.51/MBPublicScheme/default.svc?wsdl' using WS-Metadata Exchange or DISCO.
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.30]
Copyright (c) Microsoft Corporation. All rights reserved.

Error: Cannot obtain Metadata from http://192.168.1.51/MBPublicScheme/default.svc?wsdl

If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata pu
blishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.mic
rosoft.com/fwlink/?LinkId=65455.


WS-Metadata Exchange Error
URI: http://192.168.1.51/MBPublicScheme/default.svc?wsdl

Metadata contains a reference that cannot be resolved: 'http://192.168.1.51/MBPublicScheme/default.svc?wsdl'.

Content Type application/soap+xml; charset=utf-8 was not supported by service http://192.168.1.51/MBPublicScheme/default.svc?w
sdl. The client and service bindings may be mismatched.

The remote server returned an error: (415) Cannot process the message because the content type 'application/soap+xml; charset=
utf-8' was not the expected type 'text/xml; charset=utf-8'..


HTTP GET Error
URI: http://192.168.1.51/MBPublicScheme/default.svc?wsdl

The document was understood, but it could not be processed.
- The WSDL document contains links that could not be resolved.
- There was an error downloading 'http://s2-utdsrv07/MBPublicScheme/default.svc?xsd=xsd0'.
- The remote name could not be resolved: 's2-utdsrv07'

If you would like more help, type "svcutil /?"




Solution :

I did added the IpAddress of the machine to the DNS Manager and it worked fine for me.

If you want to use IPAddress of the machine instead of machine name in wsdl file :

Go to IIS..


Right Click on Default Website --> Edit Binings --> Host Name : IP Address of the Machine.


Or
Go to C:\WINDOWS\system32\drivers\etc\hosts.txt file
and add an entry for the machine and IPAddress.

Monday 10 January 2011

WCF, Service attribute value in the ServiceHost directive could not be found.

I'm trying to host my service with IIS 7 but I keep get this exception.
Server Error in '/WebServices' Application.
--------------------------------------------------------------------------------

Server Error in '/' Application.
--------------------------------------------------------------------------------

The type 'PublicScheme.PublicScheme', provided as the Service attribute value in the ServiceHost directive could not be found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The type 'MBPublicScheme.PublicScheme', provided as the Service attribute value in the ServiceHost directive could not be found.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[InvalidOperationException: The type 'PublicScheme.PublicScheme', provided as the Service attribute value in the ServiceHost directive could not be found.]
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +830
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +779
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +46
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +683

[ServiceActivationException: The service '/myservice/Default.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'MBPublicScheme.PublicScheme', provided as the Service attribute value in the ServiceHost directive could not be found..]
System.ServiceModel.AsyncResult.End(IAsyncResult result) +460
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +471
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +276
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +220
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4955


Solution:

This message is often due to an IIS 7 config problem. If you are used to creating a virtual directory pointing to the folder where your service resides, that no longer works. Now, you need to use the "Create Application..." option instead.

IIS7: WCF Services - .SVC do not work

I came across a problem with Windows Communication Foundation Services and IIS 7.
I deployed a .SVC file to my IIS 7.
The service worked during development on the local ASP.NET Dev Web server, but after deploying it to the server, there was an error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
The configuration section 'system.serviceModel' cannot be read because it is missing a section declaration.
After some research on Google someone suggested me to Install and register .NET3.0 with IIS7.
Execute the following command
"%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -i

http://blogs.msdn.com/b/knom/archive/2009/10/14/iis7-wcf-services-svc-do-not-work.aspx