SQL CLR Function Using Quartz.net - quartz.net

Am trying to create a CLR function and inside am using below quartz.net code snippet
public static class SqlCron
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static DateTimeOffset? GetNearestDate(SqlString expression, SqlDateTime baseDateTime)
{
if (expression.IsNull || baseDateTime.IsNull)
return (DateTime?)null;
try
{
var schedule = new CronExpression(expression.Value);
var res = schedule.GetTimeAfter(baseDateTime.Value);
return res;
//return new DateTimeOffset();
}
catch (Exception ex)
{
return (DateTime?)null;
}
}
}
When I try to register this assembly to SQL server throwing exception.
CREATE ASSEMBLY MyCron
FROM 'D:\Projects\MyCron\bin\Debug\MyCron.dll'
--WITH PERMISSION_SET = UNSAFE--UNSAFE --EXTERNAL_ACCESS --PERMISSION_SET = SAFE;
GO
CREATE FUNCTION CronNearestDate(
#Expression NVARCHAR(100),
#BaseDateTime DATETIME)
RETURNS DATETIME
AS
EXTERNAL NAME [MyCron].[MyCron.SqlCron].[GetNearestDate]
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE
GO
--Every month last day
--0 59 23 L * ? *
select dbo.CronNearestDate('0 59 23 L * ? *', GETDATE())
GO
The above will register the assembly and create the SQL clr function. But it is failed in the assembly registration itself
The error would be
Warning: The Microsoft .NET Framework assembly 'system.diagnostics.tracing, version=4.2.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a.' you are registering is not fully tested in the SQL Server hosted environment and is not supported. In the future, if you upgrade or service this assembly or the .NET Framework, your CLR integration routine may stop working. Please refer SQL Server Books Online for more details.
Msg 6586, Level 16, State 1, Line 3
Assembly 'System.Diagnostics.Tracing' could not be installed because existing policy would keep it from being used

Related

Crystal Report Error in formula This field name is not known

When I call ExportToDisk(). In some machine do well. But in some machine throw the exception.
Exceptoion
This field name is not known.
Error in File C:\Windows\TEMP\RPTH010_Report01 {C0D0E863-1741-4917-A455-B23347EA4FD6}.rpt:
Error in formula <填單日期>.
'numberVar RocDateNumber := {RPTH010_Report01.D01_APLDATE};'
This field name is not known.
This field name is not known.
Error in File C:\Windows\TEMP\RPTH010_Report01 {C0D0E863-1741-4917-A455-B23347EA4FD6}.rpt:
Error in formula <填單日期>.
'numberVar RocDateNumber := {RPTH010_Report01.D01_APLDATE};'
This field name is not known.
stack trace
CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
CrystalDecisions.CrystalReports.Engine.FormatEngine.Export(ExportRequestContext reqContext)
CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToDisk(ExportFormatType formatType, String fileName)
JcsWebSolution.Report.CRDocument.SaveToDisk()
mOffice.Models.Report.ASSET.RPTH010_Report01.PrintReport()
mOffice.Models.Report.ReportBase.PrintProcess()
My system
CrystalDecisions.CrystalReports.Engine.dll, v10.5.3700.0
CrystalDecisions.Shared.dll, v10.5.3700.0
Window Server 2012 R2
Visual Studio 2013
I try to fixed the bug by
Reinstall crystal report runtime SP12.
Checking the font is in system.
And I try to print a report without formula and it can export well. And I add the concat string formula it just broken.
My code
public class result
{
public string { get; set;}
}
public bool DoExport()
{
List<result> test = new List<result>();
test.Add(new result { test = "123" });
DataTable input = ListToDataTable(test);
input.TableName = "test";
m_RptDataSet.Tables.Add(input);
ReportDocument m_ReportDocument = new ReportDocument();
m_ReportDocument.Load(HttpContext.Current.Server.MapPath("~/RPT/test.rpt"));
m_ReportDocument.SetDataSource(input);
m_ReportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "test.pdf");
m_ReportDocument.Close();
m_ReportDocument.Dispose();
m_ReportDocument = null;
}
public DataTable ListToDataTable<T>(List<T> list)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
object[] values;
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
dt.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T item in list)
{
values = new object[props.Count];
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
concat string formula
{RPTH040_Test.test} + " test Function"
But in other machine just fine. Does anyone has the same problem?
Updated
I test a new report which have 3 records without formula. I find that the report can export, but does not show records. So I guess the main reason is that SetDataSource() doesn't work in my machine(windows 2012 R2).
I try to add the code to Web.config.
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
It still not work. Does anyone know about this?
I got the main result from SCN.
CR 10.5 (CR for VS 2008) is not compatible / tested supported with Win 2012. It is also not compatible with VS 2013.
Upgrade CR to CR for VS 2013 (13.0).
Bhushan
More detail -> Windows server 2012 R2 SetDataSource doesn't work | SCN
I got the same error in Crystal Report after making series of changes in the respective stored procedure, finally I found that I was using a field in my formulas which were removed from my sp (earlier this field was there when I have created the formula and then removed from the SP), so I updated my formula with proper updated field now and then its gone.

Deserialize Revit API

this is my first time to get my feet wet with serialization...in fact i am developing Autodesk Revit through C#.
Objective:
I need to record data to a new file on HDD, so that this file can be opened from another computer through Revit.
Procedure:
Handle all the required data.from Main class.
Instantiate and pass these data to a Serializable class.
Save to file the data from main class.
Dispose stream and set serializable class to null.
Deserialize.
Do stuff on revit on the basis of acquired data.
Problem
- the program works perfectly with no error and every thing is OK.
- press the button again to rerun the program it fails at deserialization with this error code
[A]Cons_Coor.ThrDviewData cannot be cast to [B]Cons_Coor.ThrDviewData. Type A originates from 'Cons_Coor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\Users\mostafa\AppData\Local\Temp\RevitAddins\Cons_Coor-Executing-20140820_224454_4113\Cons_Coor.dll'. Type B originates from 'Cons_Coor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\Users\mostafa\AppData\Local\Temp\RevitAddins\Cons_Coor-Executing-20140820_230011_0316\Cons_Coor.dll'.A first chance exception of type 'System.NullReferenceException' occurred in Cons_Coor.dll
Main Class:
///main class
.....
.....
ThrDviewData v3ddata = new ThrDviewData(); ///instantiate a serializable class
///collect all required data
string filename = UT_helper.conpaths(UT_constants.paths.Desktop) + "\\comment2" + DateTime.Today.ToShortTimeString().Replace(":", "") + ".a4h";
using (Stream stream = File.Open(filename, FileMode.Create))
{
BinaryFormatter bformatter = new BinaryFormatter();
Debug.WriteLine("Writting Data\r\n");
bformatter.Serialize(stream, v3ddata);
stream.Close();
}
v3ddata = null;
using (Stream stream = File.Open(filename, FileMode.Open))
{
BinaryFormatter bformatter = new BinaryFormatter();
Debug.WriteLine("Reading data from file");
try
{
v3ddata = (ThrDviewData)bformatter.Deserialize(stream);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
// File.Delete(filename);
}
stream.Close();
}
....
....
///do some stuff with the acquired data
Serializable Class
public string myvariables;
public ThrDviewData()
{
myvariables = null;
}
public ThrDviewData(SerializationInfo info, StreamingContext ctxt)
{
myvariables= (String)info.GetValue("name", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("name", myvariables);
}
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
so any hints?
The Binary Serializer you're using is very tightly tied to the class you're exporting.
When you're using the Revit Addin manager to load your addin, it's making a dynamic copy of your assembly (so that you can come back and load it again while you're in the same session). When it does that, you wind up with duplicate types that have the same name (ThrDviewData). When you try to load a previously serialized binary that was from a different copy, it is still trying to map to the original type (not the new copy of the type).
Your choices are:
1. Don't use the Addin manager, just statically use your addin.
2. Use something other than the Binary serializer that is not so tightly coupled to the types (like an XML or JSON serializer - as you tried).
That's what happened...

use function like application

before in application , i used a function . i add it to my sqlserver --> database --> Programmabality ---> Function ---> Scalered-Value Function
and in the application i used , like this :
dbo.MyFunc(_txt.text);
but now i need this function in my project . its mvc4 web site .
is it possible to use like that ? and where i should add this function?
of course i did like application , but db.MyFunc() dose not recognize in my class.
so,my project is CodeFirst .
As you are using code first DB approach, code changes will be reflected in SQL server DB. So you'll have to implement it in C#
Below is one example. Got from How to: Create and Run a CLR SQL Server User-Defined Function
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
public const double SALES_TAX = .086;
[SqlFunction()]
public static SqlDouble addTax(SqlDouble originalAmount)
{
SqlDouble taxAmount = originalAmount * SALES_TAX;
return originalAmount + taxAmount;
}
}
If you just want direct access to this specific function:
public Object MyFunc(String txt_text)
{
Object result = null;
String connectionstring = "DataSource=.\SQLEXPRESS;"
+ "Initial Catalog=DEMO;"
+ "Integrated Security=True"; // or whatever you use....
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT dbo.Myfunc(#p1)", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#p1", txt_text);
result = command.ExecuteScalar();
}
}
return result;
}
That would establish a connection to the database and execute that scalar-values function, then place the result within result. This takes any other database infrastructure out of the equation and just allows you to directly call your SQL function.

How do I install custom SharePoint Timer job on MOSS

How do I install custom SharePoint Timer job on MOSS
Hello I created,
custom SharePoint Timer job,
Below in this document is my code.
I wrote and installed a lot of
webparts.
But this is the first time I write
SharePoint Timer job on MOSS.
i try to deploy it wite wspBuilder,
try to copy it to gac,
But the JOB not appear on the list JOB on
Central Administration site ,
Central Administration > Operations > Timer Job Definitions ,
how can i add it and see it on the ,
Central Administration > Operations > Timer Job Definitions
the code.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.IO;
using Microsoft.SharePoint;
namespace WSPBuilderProject1.FeatureCode
{
public class MyTimerJob : SPJobDefinition
{
public MyTimerJob()
: base()
{
this.Title = "My Timer Job";
}
public MyTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
: base(jobName, service, server, targetType)
{
this.Title = "My Timer Job";
}
public MyTimerJob(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "My Timer Job";
}
public override void Execute(Guid contentDbId)
{
using (SPWeb oWeb = SPContext.Current.Site.OpenWeb("/"))
{
SPWeb mySite = SPContext.Current.Web;
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.Lists["AuditLogCalculatedData"].Items;
int itemCount = listItems.Count;
for (int k = 0; k < itemCount; k++)
{
try
{
listItems.Delete(k);
}
catch { }
}
SPListItem item = listItems.Add();
item["FileName"] = "roi";
item["NumOfEntries"] = 10102;
item.Update();
mySite.AllowUnsafeUpdates = false;
}
}
}
}
This is the sample code which can be executed on FeatureActivated event
public override void FeatureActivated (SPFeatureReceiverProperties props) {
SPWebApplication webApp = props.Feature.Parent as SPWebApplication;
if (webApp == null)
throw new SPException("Error obtaining reference to Web application.");
// Ensure the job is not already registered.
foreach (SPJobDefinition job in webApp.JobDefinitions)
if (job.Name == JOB_NAME) job.Delete();
// Install job.
SharePointWarmupJob warmupJob = new SharePointWarmupJob(webApplication);
// Schedule the job to run every minute all the time.
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 1;
warmupJob.Schedule = schedule;
// Save changes.
warmupJob.Update();
}
The solution
If you read down the article, there is a zipped solution file (TaskLogger_CustomTimerJob.zip) which you can use and compile yourself.
VS2008 will prompt you to convert project to 2008, just do it and compile.
Building the project
The problem you can't build lies within file BuildSharePointPackage.Targets. MakeCabPath is not valid for your environment. My makecab.exe lies in C:\Windows\system32 path. I tried to change path and rebuild, but it didn't work, it somehow tried to use the old location. So i just copied makecab.exe to C:\Program Files\Microsoft Cabinet SDK\bin and it builds sucessfully.
WSPBuilder
Also, you may want to use WSPBuilder to alleviate the pain on creating SharePoint solutions. It installs visual studio extension which you can use to make wsp file and deploy from visual studio. Download WSPBuilder here, and use Walkthrough of the Visual Studio Add-in

Dependency Injection for Windows Phone 7

I was trying to use Unity 2.0 beta 2 for Silverlight in my Windows Phone 7 project and I kept getting this crash:
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.DynamicMethodConstructorStrategy() + 0x1f bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.DynamicMethodConstructorStrategy() + 0x1f bytes mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo rtci = {System.Reflection.RuntimeConstructorInfo}, System.Reflection.BindingFlags invokeAttr = Default, System.Reflection.Binder binder = null, object parameters = {object[0]}, System.Globalization.CultureInfo culture = null, bool isBinderDefault = false, System.Reflection.Assembly caller = null, bool verifyAccess = true, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller)
mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(object obj = null, System.Reflection.BindingFlags invokeAttr = Default, System.Reflection.Binder binder = null, object[] parameters = {object[0]}, System.Globalization.CultureInfo culture = null, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller) + 0x103 bytes
mscorlib.dll!System.Activator.InternalCreateInstance(System.Type type = {Name = "DynamicMethodConstructorStrategy" FullName = "Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy"}, bool nonPublic = false, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller) + 0xf0 bytes mscorlib.dll!System.Activator.CreateInstance() + 0xc bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.ObjectBuilder2.StagedStrategyChain.AddNew(Microsoft.Practices.Unity.ObjectBuilder.UnityBuildStage stage = Creation) + 0x1d bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.Unity.UnityDefaultStrategiesExtension.Initialize() + 0x6c bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.Unity.UnityContainerExtension.InitializeExtension(Microsoft.Practices.Unity.ExtensionContext context = {Microsoft.Practices.Unity.UnityContainer.ExtensionContextImpl}) + 0x31 bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.Unity.UnityContainer.AddExtension(Microsoft.Practices.Unity.UnityContainerExtension extension = {Microsoft.Practices.Unity.UnityDefaultStrategiesExtension}) + 0x1a bytes
Microsoft.Practices.Unity.Silverlight.dll!Microsoft.Practices.Unity.UnityContainer.UnityContainer() + 0xf bytes
Thinking I could resolve it I've tried a few things but to no avail.
Turns out that this is a rather fundamental problem and my assumption that Windows Phone 7 is Silverlight 3 + Some other stuff is wrong. This page describes the differences between Mobile Silverlight and Silverlight 3.
Of particular interest is this:
The System.Reflection.Emit namespace is not supported in Silverlight for Windows Phone.
This is precisely why Unity is crashing on the phone, DynamicMethodConstructorStrategy class uses System.Reflection.Emit quite extensively...
So the question is, what alternative to Unity is there for Windows Phone 7?
So, in the spirit of answering my own questions, I've put together a simple DI container (using Activator.CreateInstance for instantiating things). All this does is support type registrations and instance registrations.
Seems to be doing the job. Will worry about performance later.
public class DuplicateRegistrationException : Exception {
public DuplicateRegistrationException() { }
public DuplicateRegistrationException(string message) : base(message) { }
public DuplicateRegistrationException(string message, Exception inner) : base(message, inner) { }
}
public interface IDIContainer {
void Register<TIntf, TClass> () where TIntf: class where TClass : TIntf;
TIntf Resolve<TIntf>() where TIntf : class;
void RegisterInstance<TIntf>(TIntf instance);
}
public class DIContainer : IDIContainer{
Dictionary<Type, Type> m_TypeRegistrations;
Dictionary<Type, object> m_InstanceRegistrations;
public DIContainer() {
m_TypeRegistrations = new Dictionary<Type, Type>();
m_InstanceRegistrations = new Dictionary<Type, object>();
}
#region IDIContainer Members
public void Register<TIntf, TClass>()
where TIntf : class
where TClass : TIntf {
if(DoesRegistrationExist<TIntf>())
throw new DuplicateRegistrationException("Can only contain one registration per type");
m_TypeRegistrations.Add(typeof(TIntf), typeof(TClass));
}
public TIntf Resolve<TIntf>() where TIntf : class {
return Resolve(typeof(TIntf)) as TIntf;
}
private object Resolve(Type type) {
if(!m_TypeRegistrations.ContainsKey(type)) {
if(!m_InstanceRegistrations.ContainsKey(type))
throw new NotSupportedException("Cannot find registration for type " + type.FullName + ".");
else
return m_InstanceRegistrations[type];
} else {
var createdType = m_TypeRegistrations[type];
ConstructorInfo[] constructors = createdType.GetConstructors();
ConstructorInfo mostSpecificConstructor = null;
foreach(var c in constructors) {
if(mostSpecificConstructor == null || mostSpecificConstructor.GetParameters().Length < c.GetParameters().Length) {
mostSpecificConstructor = c;
}
}
List<object> constructorParameters = new List<object>();
foreach(var a in mostSpecificConstructor.GetParameters()) {
constructorParameters.Add(Resolve(a.ParameterType));
}
return Activator.CreateInstance(createdType, constructorParameters.ToArray());
}
}
private bool DoesRegistrationExist<T>() {
return m_InstanceRegistrations.ContainsKey(typeof(T)) || m_TypeRegistrations.ContainsKey(typeof(T));
}
public void RegisterInstance<TIntf>(TIntf instance) {
if(DoesRegistrationExist<TIntf>()) {
throw new DuplicateRegistrationException("Can only contain one registration per type");
}
m_InstanceRegistrations.Add(typeof(TIntf), instance);
}
#endregion
Funq has been in development for over a year and now has a 1.0 release. It's designed to be fast and run under Compact Framework and Windows Phone 7. Another big advantage is that the author has done great a screencast series explaining its development process using TDD which is very informative!
As an aside, the most recent performance tests that I can find are from March 2009 showing it beating the pants off Unity, Autofac, Ninject, and StructureMap. I'm trying to locate more recent tests and will update this post if I do.
If you cannot find an IOC container that works on Windows Phone 7 (and I wouldn't be surprised you cannot) then I'd suggest going with a different DI strategy.
I just started putting together a Windows Phone 7 Extension Tools project on codeplex. The current version checked in supports IoC with implicit DI along with the Common Service Locator to allow complete abstraction of your code and the container they use.
Check it out over at:
http://wp7.codeplex.com
Cheers,
Simon Hart
The OpenNETCF.IoC framework works on Windows desktop, Mono, Windows Mobile, Windows Phone 7 and MonoTouch. I'm a fan of code reuse.
It's modelled after the SCSF/CAB (in object model, not crappy perf), so many of those tutorials are valid and you can leverage existing knowledge and code assets.
Despite Mark Seeman says "the world doesn’t need yet another container" in his excellent book "Dependency Injection in .NET", I decided to implement my own DI container for WP7 which provides the major DI features:
object composition
lifetime management
interception which allows you to aspect-oriented programming approaches
The container is the part of PhoneCore Framework, which you can find here:
http://phonecore.codeplex.com

Resources