Using WF to send message to Windows Server ServiceBus - c#

I'm trying to send messages to a local Topic created in Windows Server ServiceBus.
I started from examples by Roman Kiss and Paolo salvatori.
I'm stuck with the following exception:
Service namespace cannot be null or empty.
Parameter name: serviceNamespace
This is the service:
[ServiceContract]
public interface INotificationService
{
[OperationContract(Action = "*", IsOneWay = true)]
void Process(string notification);
}
My config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<system.serviceModel>
<extensions>
<!-- In this extension section we are introducing all known service bus extensions. User can remove the ones they don't need. -->
<behaviorExtensions>
<add name="connectionStatusBehavior" type="Microsoft.ServiceBus.Configuration.ConnectionStatusElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="serviceRegistrySettings" type="Microsoft.ServiceBus.Configuration.ServiceRegistrySettingsElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</behaviorExtensions>
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="tcpRelayTransport" type="Microsoft.ServiceBus.Configuration.TcpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpsRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpsRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="onewayRelayTransport" type="Microsoft.ServiceBus.Configuration.RelayedOnewayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingElementExtensions>
<bindingExtensions>
<add name="basicHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.BasicHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="webHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WebHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="ws2007HttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WS2007HttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netTcpRelayBinding" type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netOnewayRelayBinding" type="Microsoft.ServiceBus.Configuration.NetOnewayRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netEventRelayBinding" type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="sharedSecretCredentials">
<transportClientEndpointBehavior>
<tokenProvider>
<sharedSecret
issuerName="ServiceBusDefaultNamespace"
issuerSecret="--PrimarySymmetricKey retrieved with Get-SBNamespace--" />
</tokenProvider>
</transportClientEndpointBehavior>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint name="TopicPublisher"
address="sb://[machinename]/ServiceBusDefaultNamespace/NotificationService"
binding="netMessagingBinding"
contract="INotificationService"
behaviorConfiguration="sharedSecretCredentials" />
</client>
</system.serviceModel><appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<!--<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedSecretIssuer=owner;SharedSecretValue=[your secret]" />-->
</appSettings>
</configuration>
This is my ServiceBus.config file (required to avoid a "The Uri provided [machinename] does not match Service Bus domain: servicebus.windows.net." Exception, look here):
<?xml version="1.0" encoding="utf-8"?> <!-- the root web configuration file -->
<configuration>
<Microsoft.ServiceBus>
<relayHostName>[machinename]</relayHostName>
<stsHostName>[machinename]</stsHostName>
<acmHostName>[machinename]</acmHostName>
</Microsoft.ServiceBus>
</configuration>
This is the very simple workflow:
And finally this is the console:
class Program
{
static void Main(string[] args)
{
Activity publisher = new Publisher();
while (true)
{
Console.WriteLine("Type ctrl+q to exit or enter to insert a notification");
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Q && key.Modifiers == ConsoleModifiers.Control)
{
break;
}
Console.WriteLine();
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine("Please enter the notification");
}
else
{
Console.WriteLine("Sorry, I didn't understand!");
continue;
}
var notification = Console.ReadLine();
var notificationMessage = new BrokeredMessage(notification);
var inputs = new Dictionary<string, object> { { "Notification", notificationMessage } };
try
{
WorkflowInvoker.Invoke(publisher, inputs);
}
catch (Exception exception)
{
Console.WriteLine("Error: " + exception);
}
}
}
}
I created the NotificationService Topic using Service Bus Explorer 2.1.
The Azure SDK version is 2.1.4 installed via NuGet and I'm using Service Bus for Windows Server 1.1

Related

WCF service relative uri without .svc

I have a solution with 3 projects:
MEProject.WCF.ServiceLayer (Service-Implementation)
MEProject.WCF.HostConsole (Console Application which can host the service)
MEProject.WCF.HostIIS (WCF Service Application)
My goal is that I can switch between the 2 projects without changing the uri (the endpoint configurations) in the client project. Well, the problem is, if I start the console application, the endpoints are
http://localhost:8080/MultipleEndpointService/FirstEndpoint
http://localhost:8080/MultipleEndpointService/SecondEndpoint
But if I start the WCF service application, the endpoints are
http://localhost:8080/MultipleEndpointService.svc/FirstEndpoint
http://localhost:8080/MultipleEndpointService.svc/SecondEndpoint
As you can see, the difference is the ".svc". Now my question: How can I tell the WCF service application to act like the console application and not to have the ".svc" in the uri?
Here is the code I use to get the multiple endpoints in the console application:
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
serviceHostBase.ChannelDispatchers.ToList().ForEach(channelDispatcher =>
{
ChannelDispatcher dispatcher = channelDispatcher as ChannelDispatcher;
if (dispatcher != null)
{
dispatcher.Endpoints.ToList().ForEach(endpoint =>
{
endpoint.DispatchRuntime.InstanceProvider = new CallBackInstanceProvider(serviceDescription.ServiceType, InstanceCreator);
});
}
});
}
And here is the WCF service application web.config:
<system.serviceModel>
<services>
<service name="MEProject.Service.WCF.HostIIS.MultipleEndpointService">
<endpoint name="FirstEndpoint" address="FirstEndpoint" binding="basicHttpBinding" contract="MEProject.Service.WCF.ServiceLayer.IFirstEndpoint"/>
<endpoint name="SecondEndpoint" address="SecondEndpoint" binding="basicHttpBinding" contract="MEProject.Service.WCF.ServiceLayer.ISecondEndpoint"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MultipleEndpointService" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Thanks in advance for your response!
for running a WCF without the SVC extension you will need to use routing
for example i have a service named MultipleEndpointService.svc and i want to get the service like the following:
.../MultipleEndpointService/FirstEndpoint
we can do it like this:
Global.asax:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("MultipleEndpointService/FirstEndpoint", new ServiceHostFactory(), typeof(MultipleEndpointService)));
}
}
MultipleEndpointService.svc.cs:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MultipleEndpointService : IMultipleEndpointService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Web.config (for IIS7):
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd"/>
</handlers>
<directoryBrowse enabled="true"/>
</system.webServer>
source
Try URL ReWriting :
<system.webServer>
<!-- Other stuff here -->
<rewrite>
<rules>
<!-- Rewrite requests to /MultipleEndpointService.svc to /MultipleEndpointService -->
<rule name="MultipleEndpointService" stopProcessing="true">
<match url="MultipleEndpointService.svc(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite" url="/MultipleEndpointService{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>

Session getting lost after publishing (works on dev machine)

I'm working on a Holiday Tracker application and one specific thing is killing the whole "page life cycle".
In my User Scheduler, where every user can insert his vacation, sometimes it's working (and so he can insert/delete/edit and view his vacation). There is also a Vacation page (same story there, just with a grid).
But sometimes the session that is set is getting lost. If I'm debugging with Visual Studio 2012, it's working. But if I publish the application, it's not working. It just gets lost somehow
Code in Global.asax.cs
void Session_Start(object sender, EventArgs e) {
// Code that runs when a new session is started
if (HttpContext.Current.User != null && HttpContext.Current.User is HtUser)
{
HtUser user = (HtUser)HttpContext.Current.User;
Session["UserId"] = user.UserId;
if(user.HtDepartments.Any() && user.HtDepartments.First().HtBusinessUnit != null){
int BusinessUnitId = user.HtDepartments.First().HtBusinessUnit.BusinessUnitId;
Session["BusinessUnitId"] = BusinessUnitId;
}
}
}
I think that maybe the error is there.
Scheduler:
<%--<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">--%>
<div style="float: left; margin-right: 20px; margin-bottom: 10px;">
<asp:Label runat="server" Text="Unbooked vacation:"></asp:Label>
<asp:Label ID="lblBookedVacation" runat="server" Text=""></asp:Label>
</div>
<div style="float: right; margin-right: 20px; margin-bottom: 10px;">
<asp:Button runat="server" ID="btnExport" Text="Export to Lotus Notes" OnClientClick="Export(this, event); return false;" OnClick="btnExport_Click"></asp:Button>
</div>
<div style="clear: both;" />
<div>
<telerik:RadScheduler runat="server" ID="RadScheduler1" Width="750px" Height="700px"
DayStartTime="07:00:00" DayEndTime="18:00:00" SelectedView="WeekView" DataSourceID="dsVactationDays"
DataKeyField="VacationDayId" DataSubjectField="Title" DataStartField="FromDate" DataEndField="ToDate" OnAppointmentUpdate="RadScheduler1_AppointmentUpdate"
OnAppointmentInsert="RadScheduler1_AppointmentInsert"
OnRecurrenceExceptionCreated="RadScheduler1_RecurrenceExceptionCreated" OnTimeSlotCreated="RadScheduler1_TimeSlotCreated" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound">
<AdvancedForm Modal="true"></AdvancedForm>
<TimelineView UserSelectable="false"></TimelineView>
<TimeSlotContextMenuSettings EnableDefault="true"></TimeSlotContextMenuSettings>
<AppointmentContextMenuSettings EnableDefault="true"></AppointmentContextMenuSettings>
</telerik:RadScheduler>
</div>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:DataGrid runat="server" DataSourceID="dsVactationDays" AutoGenerateColumns="true"></asp:DataGrid>
<asp:EntityDataSource ID="dsVactationDays" runat="server" ConnectionString="name=HolidayTrackerEntities" DefaultContainerName="HolidayTrackerEntities"
EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="HtVacationDays"
Where="it.UserId == #UserId">
<WhereParameters>
<asp:SessionParameter DbType="Int32" Name="UserId" SessionField="UserId" />
</WhereParameters>
</asp:EntityDataSource>
<%--</telerik:RadAjaxPanel>--%>
Code behind
private const int AppointmentsLimit = 1;
// private HtUser paramUser;
private HtUser user;
private HtUser User
{
get
{
if (user == null)
{
user = HtUser.INIT_USER(this.Page, false);
}
return user;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
if (this.User != null) {
updateUnbookedVacationNotification();
}
}
txtID.Text = Session["UserId"] != null ? Session["UserId"].ToString() : "FUUUUU";
}
private void updateUnbookedVacationNotification() {
double avAmount = User.GetAnnualVacationAmountByYear(this.RadScheduler1.SelectedDate.Year);
double bookedAmount = User.GetBookedVacation(this.RadScheduler1.SelectedDate.Year);
this.lblBookedVacation.Text = (avAmount - bookedAmount).ToString();
}
//private void getParameters()
//{
// if (Page.Request["UserId"] != null)
// {
// int userId = Constants.TryConvert(Page.Request["userId"], this.Page);
// this.paramUser = HtUser.GetById(userId);
// }
//}
private bool ExceedsLimit(Appointment apt)
{
int appointmentsCount = 0;
foreach (Appointment existingApt in RadScheduler1.Appointments.GetAppointmentsInRange(apt.Start, apt.End))
{
if (existingApt.Visible)
appointmentsCount++;
}
return (appointmentsCount > AppointmentsLimit - 1);
}
private bool AppointmentsOverlap(Appointment appointment)
{
if (ExceedsLimit(appointment))
{
foreach (Appointment a in RadScheduler1.Appointments.GetAppointmentsInRange(appointment.Start, appointment.End))
{
if (a.ID != appointment.ID)
{
return true;
}
}
}
return false;
}
private void RegisterScript()
{
Label1.Text = "Invalid move! There are appointments arranged for this time period.";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "LabelUpdated",
"$telerik.$('.lblError').show().animate({ opacity: 0.9 }, 2000).fadeOut('slow');", true);
}
protected void RadScheduler1_AppointmentInsert(object sender, SchedulerCancelEventArgs e)
{
if (ExceedsLimit(e.Appointment))
{
e.Cancel = true;
RegisterScript();
}
else
{
int id = HtUser.GetUserIdByLogin(Page.User.Identity.Name);
e.Appointment.Attributes.Add("UserId", id.ToString());
}
}
Login Part
Global.asax.cs
protected void WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e)
{
if (Request.Cookies.Get(Constants.AUTHORIZATION_COOKIE_NAME) != null)
return;
String strUserIdentity;
FormsAuthenticationTicket formsAuthTicket;
HttpCookie httpCook;
String strEncryptedTicket;
AdLookup adLookup = new AdLookup();
strUserIdentity = e.Identity.Name;
bool loggedIn = false;
String email = null;
String role = null;
email = strUserIdentity;
HtUser userInfo = null;
if (email != null && email != "")
{
userInfo = HtUser.GetByLogin(e.Identity, email);
if (userInfo != null && userInfo.UserName.Length > 0)
{
loggedIn = true;
role = HtUser.GetUserRoleString(userInfo);
}
//Checks if user is in domain
else
{
userInfo = adLookup.GetAdUserByUsername(HtUser.getUserNameFromDomainString(email));
if (userInfo != null && userInfo.UserName.Length > 0)
{
loggedIn = true;
role = UserRoles.User;
}
}
}
//}
if (loggedIn)
{
formsAuthTicket = new FormsAuthenticationTicket(1, email, DateTime.Now,
DateTime.Now.AddMinutes(60), false, role);
strEncryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket);
httpCook = new HttpCookie(Constants.AUTHORIZATION_COOKIE_NAME, strEncryptedTicket);
Response.Cookies.Add(httpCook);
HttpContext.Current.User = userInfo;
}
else
{
HttpContext.Current.User = null;
}
Web.Config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="ConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="HolidayTrackerConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;User ID=sa;Password=123." providerName="System.Data.SqlClient" />
<add name="HolidayTrackerEntities" connectionString="metadata=res://*/Model.HolidayTracker.csdl|res://*/Model.HolidayTracker.ssdl|res://*/Model.HolidayTracker.msl;provider=System.Data.SqlClient;provider connection string="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="HolidayTrackerEntities1" connectionString="metadata=res://*/DAL.HTTracker.csdl|res://*/DAL.HTTracker.ssdl|res://*/DAL.HTTracker.msl;provider=System.Data.SqlClient;provider connection string="data source=ch-s-0008086;initial catalog=HolidayTracker;user id=sa;password=123.;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="LDAP_SERVER_NAME" value="asdasdasd" />
<add key="LDAP_USERNAME" value="asdasdas" />
<add key="LDAP_PASSWORD" value="asdasdasd" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<customErrors mode="Off" />
<authentication mode="Windows" />
<identity impersonate="false" />
<httpHandlers>
<add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
<add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
</httpHandlers>
<pages>
<controls>
<add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
</controls>
</pages>
<httpModules>
<add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" /></httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="RadUploadModule" />
<remove name="RadCompression" /><add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode" /></modules>
<handlers>
<remove name="ChartImage_axd" />
<remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
<remove name="Telerik_Web_UI_DialogHandler_aspx" />
<remove name="Telerik_RadUploadProgressHandler_ashx" />
<remove name="Telerik_Web_UI_WebResource_axd" />
<add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode" />
</handlers>
<directoryBrowse enabled="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
If you need something more, just let me know.
If you are using InProc session storage and publish your application, the application pool gets recycled by the IIS and the w3wp.exe process respawns. Your session data is then lost immediately.
If that is the problem you're having, and you want to avoid it, there are options for storing your session elsewhere (such as in a database). See the MSDN article on ASP.NET Session-State Modes for more information.

session abandon is not working in ASP.NET

I have developed a web site and I store data in session.If a user abondan the session,I have to set the data in session.
Logout.aspx :
protected void Page_Load(object sender, EventArgs e)
{
try
{
WebUser user = (WebUser)Session["User"];
Session["User"] = null;
Session.Abandon();
if (user != null)
SentiWordnetUtils.LogYaz(user.uAdi + "\t Çıkış Yaptı");
if ((Request.Cookies["OturumRef"] != null))
Response.Cookies["OturumRef"].Value = string.Empty;
Response.Redirect("Login.aspx");
}
catch (Exception ex)
{
LogYaz( "Oturum Sonlandırma Hatası "+ex.Message.ToString());
}
}
session_end function in global.asax :
void Session_End(object sender, EventArgs e)
{
List<TBL_SentiWordNet> tempList = (List<TBL_SentiWordNet>)Session["listProcess"];
if (tempList == null)
return;
using (DataClassesDataContext dc = new DataClassesDataContext())
{
foreach (TBL_SentiWordNet word in tempList)
{
var a = (from i in dc.TBL_SentiWordNets where i.id == word.id select i).FirstOrDefault();
a.state = 0;
}
dc.SubmitChanges();
}
Session["listProcess"]= null;
Session["User"] = null;
}
This code is working on local but isn't working on IIS. a.state never isn't 0
web.config:
<?xml version="1.0" encoding="UTF-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<sessionState mode="InProc" timeout="30" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
</system.web>
<connectionStrings>
<add name="myconnectionstring" connectionString="Data Source=127.0.0.1;Initial Catalog=mydb;Persist Security Info=True;User ID=userID;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="default.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
Session End never truly fires, because when it does execute, it's after the page request is complete and the request has already been sent to the client.
You'll need to do the session_end code in your page, or in a base page class (very handy for this sort of thing).
See the following S.O. links:
Session_End does not fire?
What is the difference between Session.Abandon() and Session.Clear()

Format ApplicationData in Service Trace Viewer as XML

I'm using TraceSource to log information to a XmlWriterTraceListener. The message I'm logging is a XML, however, when I view the message in Service Trace Viewer, it's not displayed as a XML, it's displayed as a string. Is there a way to do this?
Here is my app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="system.framework.db.utility" switchName="switchInformation">
<listeners>
<remove name="Default" />
<add name="arquivoXml" />
</listeners>
</source>
</sources>
<switches>
<add name="switchErro" value="Error"/>
<add name="switchInformation" value="Information"/>
</switches>
<sharedListeners>
<add name="arquivoXml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="C:\Temp\trace.svclog">
</add>
</sharedListeners>
</system.diagnostics>
</configuration>
Below is my code:
namespace system.framework.db.utility.sqlserver
{
internal class SqlDBTransManager : IDBManagerConnection
{
private static readonly TraceSource ts = new TraceSource("system.framework.db.utility");
private void RunSqlInternal(String pSql, DBManagerParams pDBManagerParams, DBManagerConnection pTransac)
{
//Lots of code, and below is the log
StringBuilder sb = new StringBuilder(1000);
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter xml = XmlWriter.Create(sb, settings))
{
xml.WriteStartDocument(true);
xml.WriteStartElement("log");
xml.WriteAttributeString("Método", "RunSql");
xml.WriteString(pSql);
xml.WriteEndElement();
xml.WriteEndDocument();
xml.Flush();
}
ts.TraceEvent(TraceEventType.Information, 1, sb.ToString());
oCommand.ExecuteNonQuery();
}
}
}
And below is how it's showing in Service Trace Viewer
Is there anyway so that what's under the <ApplicationData> tag is formatted as a XML?
EDIT
I opened the svcfile, and I saw that the string is not encoded properly. Why isn't it?
<ApplicationData><log Método="RunSql">drop procedure dbo.spfwug_in_controle_versao</log></ApplicationData>
No need to clutter your code with the enterprise library; just use the TraceData() method of the TraceSource passing an XPathNavigator as the object argument:
TextReader reader = new StringReader(message);
var xml = new XPathDocument(reader).CreateNavigator();
this.traceSource.TraceData(TraceEventType.Information, -2, xml);
I was able to do this dumping the TraceSource, and using the Enterprise Library 5.0. It was a XmlLogEntry that solved my problem. Below is the code:
internal class SqlDBTransManager : IDBManagerConnection
{
private void RunSqlInternal(String pSql, DBManagerParams pDBManagerParams, DBManagerConnection pTransac)
{
////Lots of code, and below is the log
XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
using (XmlWriter xml = nav.AppendChild())
{
xml.WriteStartElement("log");
xml.WriteAttributeString("Método", "RunSql");
xml.WriteString(pSql);
xml.WriteEndElement();
xml.Flush();
}
XmlLogEntry entry = new XmlLogEntry();
entry.Xml = nav;
entry.Priority = 1;
entry.Categories = new String[] { "DB" };
entry.Severity = TraceEventType.Information;
Logger.Write(entry);
oCommand.ExecuteNonQuery();
}
}
After that, I configure a XML Trace Listener in the web.config:
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="System.ServiceModel" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add name="XML Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.XmlTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.XmlTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
fileName="c:\\temp\\trace_framework.svclog" traceOutputOptions="DateTime, Timestamp, ProcessId, ThreadId" />
</listeners>
<categorySources>
<add switchValue="All" name="System.ServiceModel">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="XML Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
After this, the XML that I send is correctly formatted as a XML in the svclog format.

FormsAuthentication and Roles problems

What is this garbage in the URL? After login I am directed to:
http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/
When I debug I see that in Global.asax as well as AccountController my userRoles/accessLevel are correctly being found and inserted as part of the authentication ticket. My attributes set required roles to view the action. GET loads and when I save POST prompts for login which continually loops. Any idea what's goin on? Also, when I output my authTicket.UserData I see my roles (Author|Admin) yet HttpContext.User.IsInRole("Author"); && HttpContext.User.IsInRole("Author"); return false. Do I need roleManager enabled in web.config? And what do I set it to given me placing this info in the ticket?
SpotlightsController.cs:
// GET: /Spotlights/Edit/5
[Authorize(Roles="Author,Admin")]
public ActionResult Edit(int id)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
return View(new SpotlightFormViewModel(spotlight));
}
//
// POST: /Spotlights/Edit/5
[Authorize(Roles="Author,Admin"), HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
try
{
spotlight.ModifiedDate = DateTimeOffset.Now;
UpdateModel(spotlight);
spotlightRepository.Save();
return RedirectToAction("Details", new { id = spotlight.SpotlightID });
}
catch
{
ModelState.AddRuleViolations(spotlight.GetRuleViolations());
return View(new SpotlightFormViewModel(spotlight));
}
}
Global.asax.cs:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null) &&
HttpContext.Current.User.Identity.IsAuthenticated &&
HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsIdentity userIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
String[] userRoles = authTicket.UserData.Split('|');
HttpContext.Current.User = new GenericPrincipal(userIdentity, userRoles);
}
}
AccountController.cs:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
//string accessLevel = userRepository.FindUserByCWID(model.UserName).AccessLevel.LevelName;
string accessLevel = userRepository.FindUserByCWID(model.UserName).Roles;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
model.UserName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(30), //Expiration
model.RememberMe, //Persistent
accessLevel); // add roles?
string encTicket = FormsAuthentication.Encrypt(authTicket);
this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="devConnectionString" snip"
providerName="System.Data.SqlClient" />
<add name="ADConnectionString" connectionString="LDAP://my.domain/DC=my,DC=domain"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" connectionProtection="Secure"
enablePasswordReset="false" maxInvalidPasswordAttempts="1" passwordAttemptWindow="15"
passwordAnswerAttemptLockoutDuration="1" minRequiredNonalphanumericCharacters="0" attributeMapEmail="mail"
/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false" defaultProvider="MySqlRoleProvider">
<providers>
<clear/>
<add name="MySqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="myApp" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Cookies were not being used for some reason. Set cookieless="UseCookies" in web.config and all is working :)

Categories