fluent migrator is not creating synonym - c#

I am using Fluent Migrator 1.2.1
and i am getting exception while i am trying to create synonym
Object reference not set to an instance of an object.
StackTrace :
at FluentMigrator.Builders.Execute.ExecuteExpressionRoot.Sql(String sqlStatement)
at Tavisca.Catapult.Database.Rates.Migrations._004TagsAtProductLevel.Up() in d:\Projects\IMS\Git Source\tavisca-catapult-databases\Tavisca.Catapult.Database.Migrations\Tavisca.Catapult.Database.Rates\Migrations\004TagsAtProductLevel.cs:line 27
at Tavisca.Catapult.Database.Migrator.Program.Main(String[] args) in d:\Projects\IMS\Git Source\tavisca-catapult-databases\Tavisca.Catapult.Database.Migrations\Tavisca.Catapult.Database.Migrator\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
migration code is as follows
var contentDbConnectionString =
ConfigurationManager.ConnectionStrings["DBContent"].ConnectionString;
var ratesDbConnectionString =
ConfigurationManager.ConnectionStrings["DBRate"].ConnectionString;
var contentDbConnectionStringBuilder = new SqlConnectionStringBuilder(contentDbConnectionString);
var sqlConnectionBuilder = new SqlConnectionStringBuilder(ratesDbConnectionString);
var command = "CREATE SYNONYM [dbo].[Table1] FOR [" + sqlConnectionBuilder.DataSource + "].[" + contentDbConnectionStringBuilder.InitialCatalog + "].[dbo].[Table1];" +
"CREATE SYNONYM [dbo].[Table2] FOR [" + sqlConnectionBuilder.DataSource + "].["+ contentDbConnectionStringBuilder.InitialCatalog + "].[dbo].[Table2];";
Execute.Sql(command); // Exception will come here.
same script runs perfectly fine in query analyzer and synonym works too.

Related

How to get the Previous date from the Input in C#

My Code is as follows:
String DateTime = "20221002" (Format = "yyyyMMdd" )
Expected Result:
"20220930" ( Same format as above )
Code written:
public string FormatDateTime(string param1)
{
return Convert.ToDateTime(param1).AddDays(-1).ToString();
}
Exception Detail :
System.FormatException was unhandled
HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value)
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\adharmalin\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 235
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Am I missing something? I am getting a syntax error.
You can use ParseExact (or the TryParseExact if you're not sure it's valid)
public string FormatDateTime(string param1)
{
var myDate = DateTime.ParseExact(param1, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
return myDate.AddDays(-1).ToString();
}
[TestMethod]
public void TestDate()
{
String DateTime = "20221002";
Console.WriteLine(FormatDateTime(DateTime));
}

Creating a SQL server agent job via C# throws an "permission was denied on the object 'sp_add_operator' error

I am trying to create a SQL Server Agent job from simple windows console application but I'm receiving an The EXECUTE permission was denied on the object 'sp_add_operator', database 'msdb', schema 'dbo'. error. Steps are, define & create operator, job, job steps & job schedule. I am receiving an error on creating operator step. I've checked into SQL where I can see that access are granted to me but not sure why I am getting this error.
Code:
static void Main(string[] args)
{
Server srv = new Server();
srv.ConnectionContext.ConnectionString = "MyConnectionString";
srv.ConnectionContext.Connect();
Operator op = new Operator(srv.JobServer, "Test_Operator");
op.NetSendAddress = "Network1_PC";
op.Create(); // Error
Job jb = new Job(srv.JobServer, "Test_Job");
jb.OperatorToNetSend = "Test_Operator";
jb.NetSendLevel = CompletionAction.Always;
jb.Create();
JobStep jbstp = new JobStep(jb, "Test_Job_Step");
jbstp.Command = "Test_StoredProc";
jbstp.OnSuccessAction = StepCompletionAction.QuitWithSuccess;
jbstp.OnFailAction = StepCompletionAction.QuitWithFailure;
jbstp.Create();
//Define a JobSchedule object variable by supplying the parent job and name arguments in the constructor.
JobSchedule jbsch = new JobSchedule(jb, "Test_Job_Schedule");
jbsch.FrequencyTypes = FrequencyTypes.Daily;
jbsch.FrequencySubDayTypes = FrequencySubDayTypes.Minute;
jbsch.FrequencySubDayInterval = 30;
TimeSpan ts1 = new TimeSpan(9, 0, 0);
jbsch.ActiveStartTimeOfDay = ts1;
TimeSpan ts2 = new TimeSpan(17, 0, 0);
jbsch.ActiveEndTimeOfDay = ts2;
jbsch.FrequencyInterval = 1;
System.DateTime d = new System.DateTime(2003, 1, 1);
jbsch.ActiveStartDate = d;
jbsch.Create();
}
Error:
Microsoft.SqlServer.Management.Smo.FailedOperationException was unhandled
HelpLink=http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.3000.0+((SQL11_PCU_Main).121019-1322+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Create+Operator&LinkId=20476
HResult=-2146233088
Message=Create failed for Operator 'Test_Operator'.
Source=Microsoft.SqlServer.Smo
Operation=Create
StackTrace:
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl()
at Microsoft.SqlServer.Management.Smo.Agent.Operator.Create()
at JobUtilityTester.Program.Main(String[] args) in c:\Personal\Sample Projects\SQLServerJobUtility\JobUtilityTester\Program.cs:line 56
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: Microsoft.SqlServer.Management.Common.ExecutionFailureException
HResult=-2146233087
Message=An exception occurred while executing a Transact-SQL statement or batch.
Source=Microsoft.SqlServer.ConnectionInfo
StackTrace:
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(StringCollection sqlCommands, ExecutionTypes executionType)
at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQuery(StringCollection queries)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.ExecuteNonQuery(StringCollection queries, Boolean includeDbContext)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImplFinish(StringCollection createQuery, ScriptingPreferences sp)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
**Message=The EXECUTE permission was denied on the object 'sp_add_operator', database 'msdb', schema 'dbo'.**
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=229
Procedure=sp_add_operator
Server=10.1.201.164
State=5
StackTrace:
at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType)
InnerException:
Screen Shots :

How can I use rebus with simpleinjector

In my company we are using SimpleInjector as our IoC framework and are now looking at using Rebus as a wrapper for sending messages via RabbitMq. I am looking for help in creating a working example. I have tried the following code:
using Rebus.Activation;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Pipeline;
using Rebus.RabbitMq;
using Rebus.SimpleInjector;
using SimpleInjector;
using System;
using System.Threading.Tasks;
namespace SearchType.ProjectionA
{
class Program
{
static void Main(string[] args)
{
var container = new Container();
container.Register<IContainerAdapter, SimpleInjectorContainerAdapter>();
container.Register<IHandleMessages<string>, Handler>();
var adapter = container.GetInstance<IContainerAdapter>();
var bus = Configure.With(adapter)
.Logging(l => l.ColoredConsole())
.Transport(t => t.UseRabbitMq("amqp://localhost", "simpleinjector_consumer"))
.Start();
bus.Subscribe<string>().Wait();
Console.WriteLine("Projection A listening - press ENTER to quit");
Console.ReadLine();
}
}
public class Handler : IHandleMessages<string>
{
public Task Handle(string message)
{
return Task.Run(() =>
{
Console.WriteLine(string.Format("{0} - {1}", MessageContext.Current.Message.Headers["rbs2-corr-id"], message));
});
}
}
}
When i try and run this console application I am getting the following error:
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The container can't be changed after the first call to GetInstance, GetAllInstances and Verify. The following stack trace describes the location where the container was locked:
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 34
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Source=SimpleInjector
StackTrace:
at SimpleInjector.Container.ThrowWhenContainerIsLocked()
at SimpleInjector.Container.AddRegistration(Type serviceType, Registration registration)
at SimpleInjector.Container.RegisterSingleton[TService](TService instance)
at Rebus.SimpleInjector.SimpleInjectorContainerAdapter.SetBus(IBus bus)
at Rebus.Config.RebusConfigurer.Start()
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 36
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Does anyone know what I can do to fix this? I don't want to have to declare all the dependencies myself.
Edit: thank you Steven for your reply. I have changed the code according to your answer and am now getting a different error.
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The configuration is invalid. Creating the instance for type IMessageContext failed. The registered delegate for type IMessageContext threw an exception. Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
at SimpleInjector.Container.VerifyInstanceCreation(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyThatAllRootObjectsCanBeCreated()
at SimpleInjector.Container.VerifyInternal(Boolean suppressLifestyleMismatchVerification)
at SimpleInjector.Container.Verify()
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 27
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233088
Message=The registered delegate for type IMessageContext threw an exception. Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
InnerException:
HResult=-2146233079
Message=Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=Rebus.SimpleInjector
StackTrace:
at Rebus.SimpleInjector.SimpleInjectorContainerAdapter.<SetBus>b__7()
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance()
at SimpleInjector.InstanceProducer.GetInstance()
InnerException:
The error indicates that IMessageContext can only be instantiated inside a message handler. Is there a way to ignore certain errors?
I think the exception is clear; Simple Injector prevents registration after you already resolved. Reasons for doing this are described here.
The solution is to manually create the SimpleInjectorContainerAdapter and prevent relying on the container's auto-wiring capability for the adapter:
var container = new Container();
IContainerAdapter adapter = new SimpleInjectorContainerAdapter(container);
container.Register<IHandleMessages<string>, Handler>();
var bus = Configure.With(adapter)
.Logging(l => l.ColoredConsole())
.Transport(t => t.UseRabbitMq("amqp://localhost", "simpleinjector_consumer"))
.Start();
container.Verify();

Unhandled Exception: System.ComponentModel.Win32Exception: The operation completed successfully

Whenever I try to run this code: (code shortened to keep the post short)
// Generate a random capital letter
char key = (char)(_random.Next(24) + 65);
// 50% make it lowercase
if (_random.Next(2) == 0)
{
key = Char.ToLower(key);
}
SendKeys.SendWait(key.ToString());
I get this error:
Unhandled Exception: System.ComponentModel.Win32Exception: The operation completed successfully
at System.Windows.Forms.SendKeys.SendInput(Byte[] oldKeyboardState, Queue previousEvents)
at System.Windows.Forms.SendKeys.Send(String keys, Control control, Boolean wait)
at System.Windows.Forms.SendKeys.SendWait(String keys)
at DrunkPC.Program.DrunkKeyboardThread() in c:\Users\SPC\Documents\Visual Studio 2013\Projects\DrunkPC\Program.cs:line 91
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Line 91 is:
SendKeys.SendWait(key.toString());

Null reference error when adding picturebox dynamically to tabpage

Getting the exception message:
Object Reference not set to an instance of an object.
My code is:
PictureBox myPicBox = new PictureBox();
myPicBox.Visible = true;
myPicBox.Image = Bitmap.FromFile(#"C:\Users\MyUser\Downloads\1341596825343s1jpg.jpg");
myPicBox.Dock = DockStyle.Fill;
this.MyTabPage.Controls.Add(myPicBox);
Where MyTabPage is the fourth page in a tab control. Any suggestions?
EDIT:
Stack Trace is Here
at ShipSiegeDashBoard.Form1.LoadSpaceStations() in
C:\ShipSiegeTool\ShipSiegeDashBoard\Form1.cs:line 46 at
ShipSiegeDashBoard.Form1..ctor() in
C:\ShipSiegeTool\ShipSiegeDashBoard\Form1.cs:line 31 at
ShipSiegeDashBoard.Program.Main() in
C:\ShipSiegeTool\ShipSiegeDashBoard\Program.cs:line 18 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
I suppose your MyTabPage control isn't initialized yet. You should not try to use until after it has been initialized.

Categories