Archive for category C#.net
Properties getting “k__BackingField” appended to their name in the WSDL file
Posted by shawson in .net, C#.net, WCF, Web Services on December 7th, 2009
I was finding k__backingField was being appended to all my object properties when exposed via my a WCF service, in the WSDL. The solution it turns out was simple- just had to make my class a [DataContract] and mark the properties as [DataMember].
via WCF Data Contracts and “k__BackingField” Property Naming – Nathan Bridgewater.
Making your WCF Service compatible with legacy .net 1.1 applications
Posted by shawson in .net, C#.net, WCF, Web Services on December 7th, 2009
I’m building an error tracking service which all our future web project will report to, so we can track and tag all our various systems problems from one place- this is currently done with email which is a bit of a nightmare!
According to Microsoft, traditional ASMX web services are now considered “Legacy technology” (!) so I thought I would buite the bullet and build the new services using WCF.
This was fairly painless until I tried to consume the web service in some old .net 1.1 web apps- when trying to add the web reference I received this error message;
Web ReferenceslocalhostReference.map(1): Custom tool warning: DiscoCodeGenerator unable to initialize code generator. No code generated.
I found a great article over on the MSDN – and all it takes is a small change to the web.config, fiddling with, my old friend, the httpBindings.
I had to swap out the default bindings put in by .net;
<endpoint address="" binding="wsHttpBinding" contract="HachetteErrorTracker.IErrorLog">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
For this one;
<endpoint
address=""
binding="basicHttpBinding" bindingNamespace="http://errortracker.localhost/"
contract="HachetteErrorTracker.IErrorLog"
/>
How to: Configure WCF Service to Interoperate with ASP.NET Web Service Clients.
Deep Copy Array/ Collection/ etc using serialization
A useful snippet of code I used in a web services project a while ago which i just stumbled back across recently- allows you to make a deep copy of an array, where you would normally get a shallow copy, stopping you from manipulating it independently from the source. This gives you a completely fresh and separate copy. The original is serialised to a memory, then a new instance created from the serialised representation (so obviously if it’s an array of custom objects, those objects will need to be marked serializable)
OrderItem[] order_items_clone;
using( MemoryStream ms = new MemoryStream())
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms,order_items);
ms.Seek(0 , SeekOrigin.Begin);
order_items_clone = (OrderItem[])formatter.Deserialize(ms);
}
Synchonous Yield messing up my foreach loop!
I recently got stung while debugging a colleagues code, by my lack of understanding of the Yield keyword! We had a foreach loop which looks like this;
foreach (PurchaseOrderLine aLine in PurchaseOrderLine.LoadExtractLines(extractTime, systemId)) {
//do some processing stuff...
PurchaseOrder.MarkAsExported(lastId, extractTime);
}
The LoadExtractLines returns an IEnumerable and uses yield to return each line- the stored proc it runs is quite intensive- the whole thing looks like this;
public static IEnumerable<PurchaseOrderLine> LoadExtractLines(DateTime cutOff,int systemId)
{
using (SqlConnection conn = new SqlConnection(SingleAccess.Instance.ConnectionToUse))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("Get_PurchaseOrderLinesToExtract", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CutOff", cutOff.ToString("dd MMM yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("@SystemId", systemId);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return LoadLine(reader);
}
}
}
}
}
MarkAsExported runs quite an intensive update procedure on the database. As more and more data came into the system we started to see Sql Timeouts, and upon running a trace noticed something strange. Logging the RPC:Start and Completed events of the stored procs, the Get_PurchaseOrderLinesToExtract proc which feed’s the for loop was starting, then the update was starting before the Get_ had finished- the two were running side by side, causing the timeout’s!
Turns out the foreach loop started the moment it received it’s first row, yielded back from the LoadExtractLine method- which in retrospect does make sense! The solution was to convert the Load method to populate a local List<> then return the whole thing once complete, removing the yield statement alltoghether and forcing the process to wait for the entire result set to be complete before starting the loop.
Running vb.net alongside c# in a web app
via The ASP.NET Capsule #18: Running C# & VB.NET in the same web application – Jose R. Guay Paz.
Great snippet to wack in the web.config file, which allows you to run c# and vb.net code (*spit*
) in the same web project;
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5" />
<providerOption name="WarnAsError" value="false" />
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5" />
<providerOption name="OptionInfer" value="true" />
<providerOption name="WarnAsError" value="false" />
</compiler>
</compilers>
</system.codedom>
Thycotic Design Pattern Articles
Great bunch of articles on different design patterns up on the Thycotic Blog;
Syndicating to RSS using the built in .net SyndicationFeed classes
My boss recently showed me a pretty handy bunch of classes for generating RSS and ATOM feeds, all built into dot net.
Start by adding a new reference to your project; System.Services.Web.
The SyndicationFeed class holds all the data about your feed and lets you spit everything out in a number of different formats (RSS2.0, ATOM1.0)- each item in the feed is held in a generic list of SyndicationItem objects. As I work for a publishers, I was creating an RSS feed of coming soon books so I added an extension method to my book class- ToSyndicationItem();
public static SyndicationItem ToSyndicationItem(this Book book)
{
return new SyndicationItem(book.CoverTitle + " " + book.Subtitle, book.Description, new Uri(book.GetURL()))
{
Summary = new TextSyndicationContent(book.DescriptionShort, TextSyndicationContentKind.Plaintext),
Id = book.Id.ToString(),
LastUpdatedTime = book.InsertedDate
};
}
This allows me to use all the standard select methods I already in my book class, to also populate my RSS feed. So to create the feed all I need do in my RSS.ashx handler file is;
List<Book> books = Book.GetBookPublishedBetween(DateTime.Now,DateTime.Now.AddDays( int.Parse( GroupConstants.ComingSoonMaxDays)));
List<SyndicationItem> syndicationItems = new List<SyndicationItem>();
foreach (Book book in books)
syndicationItems.Add(book.ToSyndicationItem());
feed = new SyndicationFeed(syndicationItems)
{
Title = new TextSyndicationContent("Coming Soon Titles"),
Description = new TextSyndicationContent("Forthcoming publications."),
BaseUri = new Uri(LinkHelper.GetBaseUrl())
};
var output = new StringWriter();
var writer = new XmlTextWriter(output);
new Rss20FeedFormatter(feed).WriteTo(writer);
context.Response.ContentType = "application/rss+xml";
context.Response.Write(output.ToString());
How To Display Hierarchical Data Using Nested Repeater Controls and Visual C# .NET
Just found a piece of functionality which I’ve never noticed before, for populating nested Repeaters, without doing so in the code behind with a “OnDataBound” Event.
It’s as simple as just setting the DataSource on the child repeater, to a property of the parent repeaters DataItem. For example;
<asp:Repeater ID="BookRepeater" runat="server" onitemdatabound="bibRepeater_ItemDataBound">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li>
<h1><%# DataBinder.Eval(Container.DataItem, "BookTitle")%></h1>
<asp:Repeater ID="AuthorsRepeater" runat="server" DataSource='<%# ((Book)Container.DataItem).Authors %>'>
<HeaderTemplate><h5>Author: </HeaderTemplate>
<ItemTemplate>
<a href='/AuthorDetails.aspx?id=<%# DataBinder.Eval(Container.DataItem, "Id")%>' title="<%# DataBinder.Eval(Container.DataItem, "FirstName")%> <%# DataBinder.Eval(Container.DataItem, "LastName")%>"><%# DataBinder.Eval(Container.DataItem, "FirstName")%> <%# DataBinder.Eval(Container.DataItem, "LastName")%></a>
</ItemTemplate>
<SeparatorTemplate>, </SeparatorTemplate>
<FooterTemplate></h5></FooterTemplate>
</asp:Repeater>
</li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
You may need to add a declaration to the namespace in which your entities reside, at the top of your aspx file, like this;
<%@ Import Namespace="Hachette.Entities.Orchard" %>
full details on MSDN; How To Display Hierarchical Data by Using Nested Repeater Controls and Visual C# .NET.
Asp.net nested ListView control’s, with edit functionality- example
It might not sound like that much of a tall order, but I couldn’t find a single working example of this online- there were plenty of nested listview’s simply spitting out the data, but they all seemed to fall apart when you wanted to perform CRUD operations on the records in the nested ListView.
I eventually got this going today, after spending far longer than i ever imagined i would on it- the solution in hindsight seems obvious, but they always do- figured i would post here for anyone else who gives this ago, or for when i’ve totally forgotten about this whole episode, in about a months time;
Create your two ListViews- make sure your nested list view is in the “SelectedItemTemplate” and not the “EditItemTemplate” as i tried initially (doh!). When a row is selected in the ListView, the SelectedValue (or SelectedDataKey) property is set- you can then use this to feed a parameter of the child list view’s SQL/Object/Linq/Whatever data source.
Here is the complete ASPX markup- there is no code behind used at all.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="ListViewExample._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ListView Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="QuizList" runat="server" DataSourceID="QuizData"
InsertItemPosition="LastItem" DataKeyNames="id">
<ItemTemplate>
<tr style="background-color: #E0FFFF;color: #333333;">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete"
Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</td>
<td>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:Label ID="QuizTitleLabel" runat="server" Text='<%# Eval("QuizTitle") %>' />
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr style="background-color: #E0FFFF;color: #333333;">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete"
Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:Label ID="QuizTitleLabel" runat="server" Text='<%# Eval("QuizTitle") %>' />
</td>
</tr>
<tr>
<td></td>
<td colspan="2">
<asp:ListView ID="QuestionList" runat="server" DataSourceID="QuestionData"
InsertItemPosition="LastItem" DataKeyNames="id">
<ItemTemplate>
<tr style="background-color:#DCDCDC;color: #000000;">
<td>
<asp:Button ID="DeleteButton" runat="server"
CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server"
CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:Label ID="QuestionLabel" runat="server"
Text='<%# Eval("Question") %>' />
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" />
</td>
<td>
</td>
<td>
<asp:TextBox ID="QuestionTextBox" runat="server"
Text='<%# Bind("Question") %>' />
</td>
</tr>
</InsertItemTemplate>
<LayoutTemplate>
<table id="Table2" runat="server">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="1"
style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
<tr id="Tr2" runat="server" style="background-color:#DCDCDC;color: #000000;">
<th id="Th1" runat="server">
</th>
<th id="Th2" runat="server">
Id</th>
<th id="Th3" runat="server">
Question</th>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr id="Tr3" runat="server">
<td id="Td2" runat="server"
style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
</td>
</tr>
</table>
</LayoutTemplate>
<EditItemTemplate>
<tr style="background-color:#008A8C;color: #FFFFFF;">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Cancel" />
<asp:HiddenField ID="HiddenField1" runat="server" value='<%# Bind("QuizId") %>'/>
</td>
<td>
<asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:TextBox ID="QuestionTextBox" runat="server"
Text='<%# Bind("Question") %>' />
</td>
</tr>
</EditItemTemplate>
<SelectedItemTemplate>
<tr style="background-color:#008A8C;font-weight: bold;color: #FFFFFF;">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete"
Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:Label ID="QuestionLabel" runat="server" Text='<%# Eval("Question") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
</td>
</tr>
</SelectedItemTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" />
</td>
<td>
</td>
<td>
<asp:TextBox ID="QuizTitleTextBox" runat="server"
Text='<%# Bind("QuizTitle") %>' />
</td>
</tr>
</InsertItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="1"
style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
<tr runat="server" style="background-color: #E0FFFF;color: #333333;">
<th runat="server">
</th>
<th runat="server">
Id</th>
<th runat="server">
QuizTitle</th>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server"
style="text-align: center;background-color: #5D7B9D;font-family: Verdana, Arial, Helvetica, sans-serif;color: #FFFFFF">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<EditItemTemplate>
<tr style="background-color: #999999;">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Cancel" />
</td>
<td>
<asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
</td>
<td>
<asp:TextBox ID="QuizTitleTextBox" runat="server"
Text='<%# Bind("QuizTitle") %>' />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="QuizData" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDBConnection %>"
DeleteCommand="DeleteQuiz" DeleteCommandType="StoredProcedure"
InsertCommand="UpdateQuiz" InsertCommandType="StoredProcedure" SelectCommand="GetAllQuizes"
SelectCommandType="StoredProcedure" UpdateCommand="UpdateQuiz"
UpdateCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Id" Type="Int32" />
<asp:Parameter Name="QuizTitle" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Id" Type="Int32" />
<asp:Parameter Name="QuizTitle" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="QuestionData" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDBConnection %>"
DeleteCommand="DeleteQuestion" DeleteCommandType="StoredProcedure"
InsertCommand="InsertQuestion" InsertCommandType="StoredProcedure"
ProviderName="System.Data.SqlClient" SelectCommand="GetQuestionsByQuizId"
SelectCommandType="StoredProcedure" UpdateCommand="UpdateQuestion"
UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="QuizList" Name="QuizId"
PropertyName="SelectedValue" Type="Int32" DefaultValue="" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Id" Type="Int32" />
<asp:Parameter Name="QuizId" Type="Int32" />
<asp:Parameter Name="Question" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Id" Type="Int32" />
<asp:ControlParameter ControlID="QuizList" Name="QuizId"
PropertyName="SelectedValue" Type="Int32" DefaultValue="" />
<asp:Parameter Name="Question" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
The provided URI scheme ‘http’ is invalid; expected ‘https
Posted by shawson in .net, C#.net, VB.net, Web Services on June 30th, 2009
Going from dev to live, where the dev system referenced dev version of web services, but the live system has to reference live versions which are HTTPS i recieved this error;
The provided URI scheme ‘http’ is invalid; expected ‘https
This is resolved simply by updating the web.config file and setting the security tag’s mode attribute from None to Transport;
<bindings> <wsHttpBinding> <binding name="WSHttpBinding_IWSHttpService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Transport"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="None" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings>