create auto sql script that runs in every hour - in c# or any other easy way - sql

I have simple sql script:
Select * from student where score > 60
What i am trying to do is run this above script every 1 hour and getting notified on my computer in any way possibe that above condition was met. So basically i dont want to go in there and hit F5 every hour on the above statement and see if i get any result. I am hoping someone out here has something exactly for this, if you do please share the code.

You can use Sql Agent to create a job, Sql server 2008 also has mail functionality
Open SQL Management Studio and connect to your SQL Server
Expand the SQL Server Agent node (if you don't see it, use SQL configuration manager or check services and ensure that SQL Server Agent (SQLINSTANCENAME) is started)
Right click on Jobs and choose 'New Job'
You can run a SQL statement in a job. I'll let you figure out the rest of that part (it's pretty intuitive)
You may want to send your mail using xp_sendmail
Check out the SQL documentation for xp_sendmail
http://msdn.microsoft.com/en-us/library/ms189505(v=sql.105).aspx
You might need to turn the feature on (afaik it's off by default) and you need some server/machine to deliver the mail (so you might need IIS and SMTP installed if on a local machine)
Edit:
Assuming you can't access the server and want to do this on the client side, you can create a .NET framework app or windows service to do the work for you using a schedule or a timer approach:
Schedule approach:
Create a simple command line application which does the query and mails the results, and use the windows scheduler to invoke it every hour (or whatever your interval may be)
Timer approach:
Create a simple application or windows service that will run a timer thread which does the work every x number of minutes
I'd probably just go for the former. The code would be quite simple - new console app:
static void Main(string args[])
{
// No arguments needed so just do the work
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
using(SqlCommand cmd = new SqlCommand("sql query text", conn))
{
var dr = cmd.ExecuteReader();
List<myClass> results = new List<myClass>();
// Read the rows
while(dr.Read())
{
var someValue = dr.GetString(dr.GetOrdinal("ColumnName"));
// etc
// stuff these values into myClass and add to the list
results.Add(new myClass(someValue));
}
}
}
if(results.Count > 0) // Send mail
{
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
MailMessage message = new MailMessage(
"recipient#test.com",
"sender#test.com",
"Subject",
"Body");
// Obviously you'd have to read the rows from your list, maybe override ToString() on
// myClass and call that using a StringBuilder to build the email body and append the rows
// This may throw exceptions - maybe some error handling (in any of this code) is advisable
client.Send(message);
}
}
Disclaimer: probably none of this will compile :D
Edit 2: I'd go this way as it's much easier to debug than a windows service as you can just run it from the command line. You can also pass command line arguments so you don't need an application configuration file

Related

How to send message to all players on server? (Server-side)

How would I send a message to all of the players on the server? (When trying to do so, it only outputs to the console, and I believe that is because the mod is not installed on the client side.)
I have been trying to make a mod for a 1.7.10 server (To put in a 1.7.10 mod pack) that can message all of the players online. I have looked this question up, and have not found any answers.
#SideOnly(Side.SERVER)
#SubscribeEvent
public void onDeath(PlayerEvent.Clone event)
{
if (event.wasDeath) {
final String[] messages = {"Oh boiss we got a respawner O_O", "How dare ye respawn on me?", "GAAH! You died again!", "._. Just why...", "Was taht me or waas that you? -.-","Why isn't this in hardcore mode? It should be..."};
Random random = new Random();
int index = random.nextInt(messages.length);
ChatComponentText text = new ChatComponentText(messages[index]);
ChatStyle style = new ChatStyle();
style.setColor(EnumChatFormatting.LIGHT_PURPLE);
text.setChatStyle(style);
FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendChatMsg(text);
System.out.println("Respawned");
}
}
I expect that the server will send a message to all, but only outputs to the console.
A really quick way this could be handled is to create an EventHandler for when a player joins. Then add them to an ArrayList. Then when they leave (Check for kick / quit event). Remove them from the ArrayList. By having an arraylist you can run through this and message every player.
Your 'System.out.println("Respawned");` line will only print to the console.
I believe what you are looking to do is the following:
1) Loop through all the players on the server.
2) Send each player the calculated message.
I'm not 100% sure how to access the player-list off the top of my head, but you need to access the FMLServerHandler and get the player-list, OR (the better way) access the EntityPlayer objects connected to the player's current world and do the above steps. The second method would only work for the current world, so if you wanted to access all the connections to the server, the first method is the way to go.

How to stored Emails in SQL database and queried in an ASP.NET Application

I'm creating a backup monitoring application that I am going to write in Visual Studio using ASP.NET.
The way I would like this to work is backup emails being sent from the server that has a backup monitoring solution and are stored in a SQL database (SQL Server Express, MySQL) whatever would be best for something like this. I then plan to use this data to query and show statistics such as what servers have backed up successfully for each customer, and those that have failed. Also what servers have backed up successfully most and error trends such as not enough disk space etc.
Would this be possible and if so could someone point me in the right direction wither I should start trying to get information into a database first and foremost and how to achieve that or should I start by creating the application such as login, dashboard etc. I haven't got a strong programming background we covered some Visual Basic and ASP.NET in university and I was hoping to learn a lot from this project.
I was thinking of setting up a test environment with a server running a backup product and purposely making backups fail for testing and have access to the hardware/software resources working for an IT Consultancy / Support company.
Thanks in advance!
After some searching I came across this website which has a great piece of code that reads emails from an inbox such as Gmail and stores them in an SQL database.
protected void SaveEmails(object sender, EventArgs e)
{
for (int i = 0; i < this.Emails.Count; i++)
{
string constr = ConfigurationManager.ConnectionStrings["ConString2"].ConnectionString;
string sqlStatment = "INSERT INTO [Emails] ([From],[Subject],[Body],[Date]) VALUES (#From ,#Subject,#Body,#Date)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("#From", this.Emails[i].From);
cmd.Parameters.AddWithValue("#Subject", this.Emails[i].Subject);
cmd.Parameters.AddWithValue("#Body", this.Emails[i].Body);
cmd.Parameters.AddWithValue("#Date", this.Emails[i].DateSent);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
For the architecture of this you can try creating something like this:
External systems: Will write to the sql database
Database: Only needs one table. With possibly these columns (to give you an idea)
Receiver
Sender
IsSent
BodyMessage
SentTime
Sender: A sender application/service that will query the database at regular intervals for unsent emails and send them.
If you wonder how you technically query and insert into a SQL database then that's something there are plenty of resources on.

Why can't local Windows 7 Pro machine read its own WMI values?

As part of a larger .Net 4.0 program I have a piece that queries the WMI for a list of network adapters and from that creates a list<> of physical adapters with MAC addresses.
It works on the machines I've tried it on, but when sent to the client, the list is empty. If they run IPCONFIG /ALL at a command prompt the MACs are listed.
My first thought is that there is a group policy in place preventing the enumeration, but everything I've found so far points to group policies that affects remote access through the firewall.
I've tried it locally as both a standard user and administration user, both provide the same list.
The empty query does not generate an exception.
I could ask them to go to the machines and check individual permissions, but since this seems to be a group issue that seems to be the wrong direction. What am I missing?
public static List<WmiNetworkInterfaceItem> QueryphysicalNetworkInterfaces()
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_NetworkAdapter");
List<WmiNetworkInterfaceItem> result = new List<WmiNetworkInterfaceItem>();
foreach (ManagementObject queryObj in searcher.Get()) {
if (queryObj["PhysicalAdapter"].Equals(true)) {
if (queryObj["AdapterTypeId"] != null) {
if (queryObj["AdapterTypeId"].ToString().Equals("0")) {
WmiNetworkInterfaceItem wmiNetworkInterfaceItem = new WmiNetworkInterfaceItem();
wmiNetworkInterfaceItem.Name = ManagementObjectPropertyString(queryObj["Name"]);
wmiNetworkInterfaceItem.MacAddress = ManagementObjectPropertyString(queryObj["MACAddress"]);
wmiNetworkInterfaceItem.PhysicalAdapter = queryObj["PhysicalAdapter"].Equals(true);
wmiNetworkInterfaceItem.AdapterType = ManagementObjectPropertyString(queryObj["AdapterType"]);
wmiNetworkInterfaceItem.AdapterTypeId = -1;
int.TryParse(ManagementObjectPropertyString(queryObj["AdapterTypeId"]), out wmiNetworkInterfaceItem.AdapterTypeId);
wmiNetworkInterfaceItem.Description = ManagementObjectPropertyString(queryObj["Description"]);
wmiNetworkInterfaceItem.PermanentAddress = ManagementObjectPropertyString(queryObj["PermanentAddress"]);
result.Add(wmiNetworkInterfaceItem);
}
}
}
}
return result;
}
Using the WBEMTest utility included with Windows as suggested by user atp_09 in comments, I was able to have the customer query his machine. Using this query exactly one adapter was returned in both standard and administrative user accounts indicating there was nothing in the machine preventing this from working.
SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true
Upon further review there was an error in how I later dealt with the list with a single response.

Read SQL Server Broker messages and publish them using NServiceBus

I am very new to NServiceBus, and in one of our project, we want to accomplish following -
Whenever table data is modified in Sql server, construct a message and insert in sql server broker queue
Read the broker queue message using NServiceBus
Publish the message again as another event so that other subscribers
can handle it.
Now it is point 2, that I do not have much clue, how to get it done.
I have referred the following posts, after which I was able to enter the message in broker queue, but unable to integrate with NServiceBus in our project, as the NServiceBus libraries are of older version and also many methods used are deprecated. So using them with current versions is getting very troublesome, or if I was doing it in improper way.
http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-2
https://github.com/jdaigle/servicebroker.net
Any help on the correct way of doing this would be invaluable.
Thanks.
I'm using the current version of nServiceBus (5), VS2013 and SQL Server 2008. I created a Database Change Listener using this tutorial, which uses SQL Server object broker and SQLDependency to monitor the changes to a specific table. (NB This may be deprecated in later versions of SQL Server).
SQL Dependency allows you to use a broad selection of all the basic SQL functionality, although there are some restrictions that you need to be aware of. I modified the code from the tutorial slightly to provide better error information:
void NotifyOnChange(object sender, SqlNotificationEventArgs e)
{
// Check for any errors
if (#"Subscribe|Unknown".Contains(e.Type.ToString())) { throw _DisplayErrorDetails(e); }
var dependency = sender as SqlDependency;
if (dependency != null) dependency.OnChange -= NotifyOnChange;
if (OnChange != null) { OnChange(); }
}
private Exception _DisplayErrorDetails(SqlNotificationEventArgs e)
{
var message = "useful error info";
var messageInner = string.Format("Type:{0}, Source:{1}, Info:{2}", e.Type.ToString(), e.Source.ToString(), e.Info.ToString());
if (#"Subscribe".Contains(e.Type.ToString()) && #"Invalid".Contains(e.Info.ToString()))
messageInner += "\r\n\nThe subscriber says that the statement is invalid - check your SQL statement conforms to specified requirements (http://stackoverflow.com/questions/7588572/what-are-the-limitations-of-sqldependency/7588660#7588660).\n\n";
return new Exception(messageMain, new Exception(messageInner));
}
I also created a project with a "database first" Entity Framework data model to allow me do something with the changed data.
[The relevant part of] My nServiceBus project comprises two "Run as Host" endpoints, one of which publishes event messages. The second endpoint handles the messages. The publisher has been setup to IWantToRunAtStartup, which instantiates the DBListener and passes it the SQL statement I want to run as my change monitor. The onChange() function is passed an anonymous function to read the changed data and publish a message:
using statements
namespace Sample4.TestItemRequest
{
public partial class MyExampleSender : IWantToRunWhenBusStartsAndStops
{
private string NOTIFY_SQL = #"SELECT [id] FROM [dbo].[Test] WITH(NOLOCK) WHERE ISNULL([Status], 'N') = 'N'";
public void Start() { _StartListening(); }
public void Stop() { throw new NotImplementedException(); }
private void _StartListening()
{
var db = new Models.TestEntities();
// Instantiate a new DBListener with the specified connection string
var changeListener = new DatabaseChangeListener(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
// Assign the code within the braces to the DBListener's onChange event
changeListener.OnChange += () =>
{
/* START OF EVENT HANDLING CODE */
//This uses LINQ against the EF data model to get the changed records
IEnumerable<Models.TestItems> _NewTestItems = DataAccessLibrary.GetInitialDataSet(db);
while (_NewTestItems.Count() > 0)
{
foreach (var qq in _NewTestItems)
{
// Do some processing, if required
var newTestItem = new NewTestStarted() { ... set properties from qq object ... };
Bus.Publish(newTestItem);
}
// Because there might be a number of new rows added, I grab them in small batches until finished.
// Probably better to use RX to do this, but this will do for proof of concept
_NewTestItems = DataAccessLibrary.GetNextDataChunk(db);
}
changeListener.Start(string.Format(NOTIFY_SQL));
/* END OF EVENT HANDLING CODE */
};
// Now everything has been set up.... start it running.
changeListener.Start(string.Format(NOTIFY_SQL));
}
}
}
Important The OnChange event firing causes the listener to stop monitoring. It basically is a single event notifier. After you have handled the event, the last thing to do is restart the DBListener. (You can see this in the line preceding the END OF EVENT HANDLING comment).
You need to add a reference to System.Data and possibly System.Data.DataSetExtensions.
The project at the moment is still proof of concept, so I'm well aware that the above can be somewhat improved. Also bear in mind I had to strip out company specific code, so there may be bugs. Treat it as a template, rather than a working example.
I also don't know if this is the right place to put the code - that's partly why I'm on StackOverflow today; to look for better examples of ServiceBus host code. Whatever the failings of my code, the solution works pretty effectively - so far - and meets your goals, too.
Don't worry too much about the ServiceBroker side of things. Once you have set it up, per the tutorial, SQLDependency takes care of the details for you.
The ServiceBroker Transport is very old and not supported anymore, as far as I can remember.
A possible solution would be to "monitor" the interesting tables from the endpoint code using something like a SqlDependency (http://msdn.microsoft.com/en-us/library/62xk7953(v=vs.110).aspx) and then push messages into the relevant queues.
.m

SQL Azure - Transient "ExecuteReader requires an open connection" exception

I'm using SQL Azure in a Windows Azure app running as a cloud service. Most of the time my database actions works completely fine (that is, after handling all sorts of timeouts and what not), however i'm running into a problem that seems
using (var connection = new SqlConnection(m_connectionString))
{
m_ConnectionRetryPolicy.ExecuteAction(() => connection.Open());
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM X WHERE Y = Z";
var reader = m_CommandRetryPolicy.ExecuteAction(() => command.ExecuteReader());
return LoadData(reader).FirstOrDefault();
}
}
The line that fails is the Command.ExecuteReader with an:
ExecuteReader requires an open and available Connection. The connection's current state is closed
Things that i have already considered
I'm not "reusing" an old connection or saving a connection is a member variable
There should be no concurrency issues - the repository class that these methods belong to is created each time it is needed
Have anyone else experienced this? I could of course just add this to the list of exception which would yield a retry, but I'm not very comfortable with that as
I had a bunch of these errors a few days ago (West Europe) on my production deployment, but they went away by themselves. At the same time I was seeing timeouts, throttling and other errors from SQL Azure. I assume that there was a temporary problem with the platform (or at least the server that I am running on).
You probably aren't doing anything wrong in your code, but are suffering from degraded performance on SQL Azure. Try and handle the errors, perform retries, exponential back-off, queues (to reduce concurrency), splitting your load across databases — that sort of thing.
write every thing within try and catch,finally block.
as follows:
try
{
con.open();
m_ConnectionRetryPolicy.ExecuteAction(() => connection.Open());
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM X WHERE Y = Z";
var reader = m_CommandRetryPolicy.ExecuteAction(() => command.ExecuteReader());
return LoadData(reader).FirstOrDefault();
}
con.close();
}
catch(exception ex)
{
}
finally
{
con.close();
}
Remember to close connection in finally block as well.
There is an Enterprise Library that MS has produced specifically for SQL Azure, here are some examples from their patterns and Practice.
It's similar to what you are doing, however it does more on the reliability (and these examples show how to get a reliable connection)
http://msdn.microsoft.com/en-us/library/hh680899(v=pandp.50).aspx
Are you sure it's the reader that's failing and not the opening of the connection? I'm encountering an exception when I wrap the connection.Open() in the m_ConnectionRetryPolicy.ExecuteAction().
However it works just fine for me if I skip the ExecuteAction wrapper and open the connection using connection.OpenWithRetry(m_ConnectionRetryPolicy).
And I'm also using command.ExecuteReaderWithRetry(m_ConnectionRetryPolicy) which is working for me.
I have no idea though why it's not working when wrapped in ExecuteAction though.
I believe this means that Azure has closed the connection behind the scenes, without telling the connection pooler. This is by design. So, the connection pooler gives you what it thinks is an available, open connection, but when you try to use it, it finds out it's not open after all.
This seems very clunky to me, but it's the way Azure is at the moment.