I have two tasks. The first should be execute once an hour, and the second every day at 12:00. The trigger of the first task works fine, but the second fires only if it is created a few minutes before the target time. What am I doing wrong?
The configuration of the first:
IJobDetail job = JobBuilder.Create<WatchJob>()
.WithIdentity("Job_1", "First")
.WithDescription("Job_1_First")
.UsingJobData("AppData", JsonConvert.SerializeObject("Job_1_First"))
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("Trigger_1", "First")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(1440)
.RepeatForever())
.Build();
And the second:
IJobDetail updateJob = JobBuilder.Create<UpdateJob>()
.WithIdentity("Job_1", "Second")
.WithDescription("Job_1_Second")
.UsingJobData("AppData", JsonConvert.SerializeObject("Job_1_Second"))
.Build();
ITrigger updateTrigger = TriggerBuilder.Create()
.WithIdentity("Trigger_1", "Second")
.WithDailyTimeIntervalSchedule
(t => t
.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(12, 0))
)
.Build();
Scheduler configuration:
<quartz>
<add key="quartz.scheduler.instanceName" value="Test" />
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
<add key="quartz.threadPool.threadCount" value="1" />
<add key="quartz.threadPool.threadPriority" value="2" />
<add key="quartz.jobStore.misfireThreshold" value="60000" />
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
</quartz>
It seems nothing wrong with your Trigger definition. But Quartz(2.x) is not so well written under the hood and can sometimes act really strange.
Your second Trigger is a CronTrigger and can defined in an other way.
This works for me:
ITrigger updateTrigger = TriggerBuilder.Create()
.WithIdentity("Trigger_1", "Second")
.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(12, 0))
// this line tells quartz to start the trigger immediately, you can remove it, if you don't want this behaviour
.StartAt(DateTime.Now.AddDays(-1))
.Build();
Related
How do you set the additional parameters in app.config to reflect the directory where you want to the database to be created? This posting "EF 5 + SQL Server CE 4: How to specify custom location for database file?" does it programmatically, but I want to set the parameters in the .config file.
This is what I tried to do, but failed to get it work:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.3.5" />
<parameter value="" />
<parameter value="C:\\Users\\ericq\\Documents\\Data" />
</parameters>
</defaultConnectionFactory>
Even tried:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.3.5" />
<parameter value="data source=C:\\Users\\ericq\\Documents\\Data" />
</parameters>
</defaultConnectionFactory>
and:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.3.5" />
<parameter value="data source=C:\Users\ericq\Documents\Data" />
</parameters>
</defaultConnectionFactory>
And, can't find any examples on MSDN "SqlCeConnectionFactory Constructor (String, String, String)"
So I'm assuming you need three parameters to make this work, but my format is not working according to LINQPad5 as I try to use it to figure out how to get this to work:
ArgumentException Format of the initialization string does not conform to specification starting at index 43.
The code I'm using:
using (var db = new BloggingContext())
{
Blog mMenu = (from p in db.Blogs where p.Name.Equals("Eric Miller") select p).FirstOrDefault();
if (mMenu == null)
{
// Create and save a new Blog
var name = "Eric Miller";
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
}
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
}
And the exception is triggering when I do this:
Blog mMenu = (from p in db.Blogs where p.Name.Equals("Eric Miller") select p).FirstOrDefault();
LINQPad5 App.config (Let me type it it:)
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.3.5" />
<parameter value="" />
<parameter value="C:\\Users\\ericq\\Documents\\Data" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.3.5" type="System.Data.Entity.SqlServerCompact.Legacy.SqlCeProviderServices, EntityFramework.SqlServerCompact.Legacy" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.3.5" />
<add name="Microsoft SQL Server Compact Data Provider 3.5" invariant="System.Data.SqlServerCe.3.5" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
Thanks!...
Just add a connectionString to your config with the same name as your context:
<connectionStrings>
<add name="BloggingContext"
providerName="System.Data.SqlServerCe.3.5"
connectionString="data source=C:\data\eric.sdf;" />
</connectionStrings>
I am using Kendo.Mvc dll and below is my .cshtml
#using Kendo.Mvc.UI
#model SupplierPortal.RedirectionApp.Models.SiteDetailViewModel
#using System.Web.Optimization
#{
ViewBag.Title = "Index";
Layout = null;
}
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
#*<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.20/jquery-ui.min.js" type="text/javascript"></script>*#
#*<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common-bootstrap.min.css" />*#
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
<script src="//kendo.cdn.telerik.com/2016.2.714/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/kendo.aspnetmvc.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<div>
#(Html.Kendo().Grid<SupplierPortal.RedirectionApp.Models.SiteDetailViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Title("Name");
columns.Bound(p => p.gender).Title("Gender");
columns.Bound(p => p.designation).Title("Designation").Width("300px");
columns.Bound(p => p.department).Title("Department").Width("300px");
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Navigatable()
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax()
.Model(model =>
{
//model.Id(x => x.id);
})
.Read(read => read.Action("Employee_Read", "Home")) // Set the action method which will return the data in JSON format
)
)
</div>
Below is my controller
public ActionResult Index([DataSourceRequest]DataSourceRequest request)
{
string nasaUserId = "vlc00072";
var _prd = _redirectionService.GetSiteDetailsForAppUser(nasaUserId);
_siteDetailViewModel.SiteDetailList = _prd;
return Json(_siteDetailViewModel, JsonRequestBehavior.AllowGet);
}
I have also added Kendo.MVC reference in Views Web.Config like below
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="SupplierPortal.RedirectionApp" />
<add namespace="Kendo.Mvc" />
</namespaces>
and in main web.config file
<system.web>
<compilation debug="true" targetFramework="4.5.2" >
<assemblies>
<add assembly="Kendo.Mvc" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
can someone let me where I am doing wrong and why razor is not recognizing the #Html.Kendogrid() and I have also included the dll in reference.
You have to use Kendo.mvc.dll given by Telerik team. I was having the same problem by installing Kendo.MVC from nuget but it was not recognising then i have added .dll given by Telerik team. now it's working. Here is the link to download trial version and you will find the Kendo.Mvc.dll in C:\Program Files (x86)\Telerik\UI for ASP.NET MVC Q2 2016\wrappers\aspnetmvc\Binaries location after installing.
When i test my WCFservice's method by putting as query string in address bar it shows only "Endpoint not found.".Please help me where i am wrong? But a simple test method to add two numbers is running properly.I am running it on localhost.Below is my web.config
<connectionStrings>
<add name="ES_SecurityContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dev_Scheduler;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" executionTimeout="1599999" />
<customErrors mode="Off"/>
<membership defaultProvider="simple">
<providers>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
</system.web>
<system.serviceModel>
<services>
<!--<service name="Cygnus.Dev.JobDispatcherWCFService.JobDispatcherWcf">
<endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="web" contract="Cygnus.Dev.JobDispatcherWCFService.IJobDispatcherWcf"></endpoint>
</service>-->
<service name="SchedulerWcf.Scheduler" behaviorConfiguration="ServiceBehavior">
<!--<host>
<baseAddresses>
<add baseAddress=""/>
</baseAddresses>
</host>-->
<endpoint binding="webHttpBinding" contract="SchedulerWcf.IScheduler" behaviorConfiguration="webHttp"/>
<endpoint address="mex" binding="mexHttpBinding" contract="SchedulerWcf.IScheduler" />
</service>
</services>
<behaviors>
<!--<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>-->
<serviceBehaviors>
<behavior name="ServiceBehavior" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
below is the code of WCF Service
public class Scheduler : IScheduler
{
#region [Constructors]
public Scheduler()
{
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("ES_SecurityContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
#endregion
#region [Ping Test Methods]
public string GetSum(int x, int y)
{
return new JavaScriptSerializer().Serialize(new { sum = x + y, message = "This is sum" });
}
#endregion
#region [Methods]
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
Update 1: If i set the session via ajax request, this session is not available to me when the js does does a refresh of the current action. Now, if i setup a session via non ajax requests then these are available inside other controller even ajax actions as well.
Update 2: By removing and adding the session helped with this issue
<modules runAllManagedModulesForAllRequests="true">
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
I am setting up a new site, this uses forms authentication that i am validating against the active directory. On successful authentication, i put the user class in the session and it is available to me when i check it right away.
//login user and put the user in session
AuthenticationHelper.LoginUser(user, loginModel.IsRememberMe);
//just checking
var userFromSession = AuthenticationHelper.GetUserFromSession();
public static void LoginUser(User user, bool isRememberMe)
{
//login user and put user in the session
//log off first
LogOff();
//add user to session
AddUserToSession(user);
//sign in
if (!isRememberMe)
{
//Set cookie
FormsAuthentication.SetAuthCookie(user.UserId, false);
/*
GenericIdentity identity = new GenericIdentity(user.UserId);
string[] roles = { person.PersonaType };
GenericPrincipal principal = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principal;
*/
}
else
{
//Create Persistent cookie
var ticket = new FormsAuthenticationTicket(user.UserId, isRememberMe, 1);
var encrypted = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
authCookie.Expires = System.DateTime.Now.AddYears(1);
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Cookies.Add(authCookie);
}
}
}
public static void AddUserToSession(User user)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session["SignedInUser"] = user;
}
}
public static User GetUserFromSession()
{
User user = null;
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
user = (User) HttpContext.Current.Session["SignedInUser"];
}
return user;
}
However, when i refresh the page at the same very moment after login, my session is coming back as null. In this case Request.IsAuthenticated is true and User.Identity.Name has my user name in it.
I have the following in the web.config as well.
What am i missing here?
Here is the full web.config. Either i am missing something from the web.config or something is interfering with my session.
<?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=301880
-->
<configuration>
<!-- Move site specific app settings to their own environment config file inside Configs folder. Keep common settings here -->
<appSettings file="Configs\AppSettings_CurrentSprint.config">
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<machineKey validationKey="" validation="SHA1" decryption="AES" />
<sessionState mode="InProc" timeout="20" />
<authentication mode="Forms">
<forms loginUrl="~/EPT/Home" name="SalesSupport.ASPXFORMSAUTH" enableCrossAppRedirects="true" timeout="20" slidingExpiration="true" />
<!-- timeout="600" -->
</authentication>
<membership>
<providers>
<clear />
</providers>
</membership>
<profile>
<providers>
<clear />
</providers>
</profile>
<customErrors mode="Off" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="System.Web.Optimization" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<validation validateIntegratedModeConfiguration="false" />
<!--Had to set this for it to work on IIS 7-->
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<staticContent>
<!--Required to get IIS to compress javascript files-->
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
</staticContent>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
If I define the objects in XML and call var xmlApplicationContext = new XmlApplicationContext() the job is scheduled and fires. What I would like to accomplish is to do this through code as the properties will be dynamic, the method fragment below compiles and runs but the job is not scheduled. Is this possible?
// SpringJob.xml
<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<object name="emailNotification" type="Spring.Scheduling.Quartz.JobDetailObject, Spring.Scheduling.Quartz">
<property name="JobType" value="Project.Agent.Jobs.EmailNotification, Project.Agent" />
</object>
<object id="simpleTrigger" type="Spring.Scheduling.Quartz.SimpleTriggerObject, Spring.Scheduling.Quartz">
<property name="jobDetail" ref="emailNotification" />
<property name="startDelay" value="1s" />
<property name="repeatInterval" value="1s" />
<property name="repeatCount" value="0" />
</object>
<object type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz">
<property name="triggers">
<list>
<ref object="simpleTrigger" />
</list>
</property>
</object>
</objects>
// Method
var jobDetailObject = new JobDetailObject
{
JobType = new EmailNotification().GetType()
};
var simpleTrigger = new SimpleTriggerObject
{
JobDetail = jobDetailObject,
StartDelay = new TimeSpan(0, 0, 0, 1),
RepeatInterval = new TimeSpan(0, 0, 0, 1),
RepeatCount = 0
};
var scheduleTrigger = new SchedulerFactoryObject();
var triggers = new Trigger[1];
triggers[0] = simpleTrigger;
scheduleTrigger.Triggers = triggers;
scheduleTrigger.Start();
Decided to abandon the Spring.Net framework implementation of Quartz.Net instead I am using Quartz.Net directly.