How to connect to Smileupps Couchdb with MyCouch and C#? - c#

I may be wrong by the way I'm going about this, but I'm trying to connect to an online database that I'm hosting on Smileupps. I'm using CouchDB, and in my program I'm using MyCouch to try to communicate with the DB. Am I mistaken in doing this? How do I write a query to check if it works?
public void Connection()
{
using (var client = new MyCouchClient("https://couchdb-68effd.smileupps.com/_utils/", "dks-calc"))
{
// querys go here I assume
}
}
I'm not sure if I should be connecting on the MainPage.xaml.cs or the Client.cs that was generated with MyCouch.
enter image description here

When you connect to CouchDB, don`t use the GUI link. Test something like this :
new MyCouchClient("https://couchdb-68effd.smileupps.com/", "dks-calc")

Related

iisreset over a list of servers programmatically

I want to perform iisreset programmatically from C# code over a list of servers with account having privilege to do that.
It's easy to do that for local machine for example that's a sample code:
// using ...
using System.Diagnostics;
public class YourForm : Form
{
// ...
private void yourButton_Click(object sender, EventArgs e)
{
Process.Start(#"C:\WINDOWS\system32\iisreset.exe", "/noforce");
}
// ...
}
Also:
using System.ServiceProcess;
using (ServiceController controller = new ServiceController())
{
controller.MachineName = “My local or remote computer name”;
controller.ServiceName = “IIS Service Name”; // i.e “w3svc”
if (controller.Status != ServiceControllerStatus.Running)
{
// Start the service
controller.Start();
Log.Debug(“IIS has been started successfully, now checking again for webservice availability”);
}
else
{
// Stop the service
controller.Stop();
// Start the service
controller.Start();
Log.Debug(“IIS has been restarted successfully”);
}
}
but how to perform this for more than one server.
Your first code snippet should work perfectly taking in considerations that there is no need to provide the full path of iisreset command.
Actually, you don't need that full path while calling IISRESET from CMD or Run tool. So, it is the same call.
Regarding user privilege, there are 2 approaches
You can pass desired user as an argument to Process.Start
Process.Start("iisreset", "server1", "admin", "admin password", "domain");
You can just call Process.Start as you did in your code, then make sure to run your application with the suitable user
I tried below and it worked perfectly
static void Main(string[] args)
{
string[] servers = LoadServersFromFile();
foreach (string server in servers)
{
Process.Start("iisreset", server.Trim());
}
}
private static string[] LoadServersFromFile()
{
//just listed all servers comma separated in a text file, change this to any other approach fits for your case
TextReader reader = new StreamReader("Servers.txt");
return reader.ReadToEnd().Split(',');
}
You probably need an impersonator to execute the above code.
I think the username and password used in the impersonator should have admin rights for that server (which you do).
You probably also need to remotely access the machine and then execute your code.
The post here, here and here might be of help to you.
Will update this post if something more useful comes to my mind.
EDIT:
You can try out the following steps:
Create a windows service with code for restarting the IIS
Deploy this service on all the servers for which you need to reset the IIS
Keep this service turned off
Remotely access this service (code to access services remotely is given in one of the posts above)
Start and stop the service. This will execute the code for resetting the IIS. Code for this is given here
Hope this helps.

C#, convert a database value to a string?

I have a report that gets updated every week that needs pushed out to 30+ PC's and the number is rising each week. I am trying to figure out how to take an Access Database and push the files out from a location on our server to all of each of those PC's but what I can't wrap my head around is how to do it. I was going to use a copy command and then use the value of the PC ID in a string and enter it into the file paths. This is a little bit more advanced than I am used to working with. Here's what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet1.PCID_List' table. You can move, or remove it, as needed.
this.pCID_ListTableAdapter.Fill(this.database1DataSet1.PCID_List);
}
private void button_Close_Click(object sender, EventArgs e)
{
this.Close();
}
static void button_Run_Click(object sender, EventArgs e)
{
string reportLocationCopy = #"Location TBD";
string repLoc = #"Location TBD";
if (File.Exists(repLoc))
{
// If file already exists in destination, delete it
if (File.Exists(reportLocationCopy))
File.Delete(reportLocationCopy);
File.Copy(repLoc, reportLocationCopy);
}
}
}
}
What I would do is this:
Open a database connection that selects your required information. Then use a sqldata adapter/datatable to draw the number of rows. Then I would write a foreach statement that uses these PCs and sends the updated file. So off the top of my head...
//select query here and your connectionstring
//then fill table as seen below
SqlDataAdapter sDA = new SqlDataAdapter(query, connectionString);
DataTable table = new DataTable();
sDA.Fill(table);
foreach (DataRow row in table.Rows)
{
string pc = (row["PCs"].ToString());
//send files
}
This would be an option:
As the numbers of client PC are growing every week, why don`t you try writing web-service. It will provide the ease and central management.
Now you have two case:
If you are working on intranet, locally host your WCF service on IIS.
If you have website then create web-service for that, then your internet based remote client can access your data.
You might need three things:
WCF service
IIS hosting
Client Application
Blue sky idea here, this may not be possible for security reasons. Can you push the database files to a Dropbox account, which the other machines also reference? This would provide quick synchronization of the machines as the database files are updated.
For what it's worth...
If this is in an Enterprise, your sysadmins will have tools that can push to each PC. I've done similar things to push application releases, and they can script whatever you need.
It might be worthwhile to post the question in a Sys Admin forum like serverfault or everythingsysadmin.
If your really dead set on managing the distribution, you can have your application call a Web Service or check a shared drive on startup for a newer version of the file and download it (either ftp or straight copy).
Let the client do the lookup to avoid issues like the PC not being available. It also allows the client to cancel the load if they are in a hurry. Nothings worse that having an update forced on you when you need something quickly!

Problems connecting to a local MySQL database using C# and .NET 2.0

Newb questions incoming.
I'm running MySQL locally and I am having a really hard time connecting to it with C#.
Here's the code I'm using, much of the stuff I've tried out is commented out:
using System;
using System.Collections.Generic;
//using System.Data.Common.DbConnection;
using System.Threading;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Threading;
namespace mvpde
{
class Program
{
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
OleDbConnection con = new OleDbConnection(#"Provider=sqloledb;Data Source=127.0.0.1:3306;database=database_name;User id=id;Password=password;");
con.Open();
//Thread.Sleep(9999);
//SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//builder.DataSource = "localhost";
//builder.UserID = "hello";
//builder.Password = "password";
//builder.InitialCatalog = "db_123";
//SqlConnection thisConnection = new SqlConnection(builder.ToString());
//thisConnection.Open();
//SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
//SqlDataReader thisReader = thisCommand.ExecuteReader();
//while (thisReader.Read())
//{
// Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]);
//}
//thisReader.Close();
//thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
Thread.Sleep(9999999);
}
}
}
}
}
I've copied it nearly verbatim and tried to make it work from this site.
I have installed the MySQL on Windows 7 - I have created the user and the database I'm trying to access and I can do all this just fine using MySQL's own MySQL Workbench 5.2 CE software. I seem to have no clue what I'm doing using C# to connect to it.
All I want is to connect to it and send it a simple query like "USE DATABASE somedb" and then "SELECT TABLE sometable".
Errors I'm getting:
At first (when I used WAMP, before installing the MySQL package from mysql website) I would be able to connect once and see a login error; after that, it's as if the connection wasn't closed properly and I'd be unable to get even that far)
Now that I'm trying to connect to a MySQL instance that is created by MySQL's own software (or by running mysqld.exe) all I ever get is timeout problems\server not found\inaccessible.
Questions:
Am I using the wrong class?
What's the deal with "Provider="? where is the list of all the available variables for that part of the string? What does it mean? Why are the names involved so cryptic?
I imagined connecting to a locally-running MySQL server should be a breeze, but I've no idea what I'm doing.
Thank you.
You should use the MySql/Connector for DotNet.
Download it at this address then change your connection string accordingly.
For example "Server=127.0.0.1;Database=database_name;Uid=id;Pwd=password;Port=3306"
For other options, specific for MySQL, look at www.connectionstrings.com
have you had a look at http://www.connectionstrings.com/mysql ?
You can't use a SQL Connection object. You need a MySQL Connection object which is available in this library.http://www.connectionstrings.com/mysql
Download the MySQL Connection Library and use one of their connection strings provided on the site.
using MySql.Data.MySqlClient;
MySqlConnection myConnection = new MySqlConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Then use the connection object to initalise the connection string and connect to MySQL

Problem with WebSockets Draft

I'm having some trobule with Web Sockets and Microsoft's Draft implementation. I'm using the API provided by them for the server back and as well as the Silverlight fix for browsers that don't natively support Web Sockets. The information i'm working off of comes from http://channel9.msdn.com/Events/MIX/MIX11/HTM10 and http://html5labs.interoperabilitybridges.com/prototypes/websockets/websockets/info
My code compiles okay, it starts to open the connection, then fails. Here's my backend server code (in a C# Console App)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ServiceModel.WebSockets;
namespace ChatBackend
{
class Program
{
static void Main(string[] args)
{
var host = new WebSocketsHost<MessageHandler>();
host.AddWebSocketsEndpoint("ws://localhost:4502/MessageHandler");
host.Open();
Console.ReadLine();
}
}
}
Here's the MessageHandler class:
class MessageHandler : WebSocketsService
{
public override void OnMessage(string value)
{
string returnMessage = "You just said '" + value + "'";
Console.WriteLine(value);
SendMessage(returnMessage);
}
}
This backend part seems to work fine. Here's the client end:
$(document).ready(function () {
setTimeout(connect, 2050);
});
function connect() {
websocket = new WebSocketDraft("ws://localhost:4502/MessageHandler");
websocket.onopen = function() {
websocket.send("test");
};
websocket.onclose = function () {
alert("DIED");
};
websocket.onmessage = function(event) {
sendMessage(new message(0, event.data, 0));
};
}
EDIT: I checked my firewall and allowed the port i was using. Now the connection just hangs - it doesn't close, it doesn't open. Any ideas?
EDIT 2: I did some more research, turns out i need to remove the clientaccesspolicy.xml. Also turns out i never had it, but i WAS returning a custom 302 redirect instead of a 404 not found. Fixed that, but no progress. It just hangs.
EDIT 3: Tried turning off Anti-Virus and Firewall, no change
Thanks - let me know if i need anymore code or information up here.
Can you use Firebug or something and put a breakpoint on this line in jquery.slws.js (assuming its the one you're using!)
this.slws = slCtl.Content.services.createObject("websocket");
And then step through and see where it fails ?
Your URL definitely looks like it matches the setting on your server side. It's really hard to find any examples of WebSockets actually being used since it's still such a new technology, but from what I could follow of the only working example I could find (it was on the html5labs site), I think maybe you're trying to write to the socket before it's finished opening. In the example I found, it looked like they check the readyState property of the socket, and only try to send if readyState === 1. The socket in that example gets opened by tying into the $(document).ready event, and send gets called from a button click.
Finally got this working! Turns out i had to add clientaccesspolicy.xml to the root folder of the default website on my server. I thought i had to delete it - i misread some information and promptly forgot about it. Moral of the story: read the readme!

C# SQL server connection

HI
As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not.
Thanks Andy
Here's a little console app example that will cycle through a list of connections and attempt to connect to each, reporting success or failure. Ideally you'd perhaps want to extend this to read in a list of connection strings from a file, but this should hopefully get you started.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace SQLServerChecker
{
class Program
{
static void Main(string[] args)
{
// Use a dictionary to associate a friendly name with each connection string.
IDictionary<string, string> connectionStrings = new Dictionary<string, string>();
connectionStrings.Add("Sales Database", "< connection string >");
connectionStrings.Add("QA Database", "< connection string >");
foreach (string databaseName in connectionStrings.Keys)
{
try
{
string connectionString = connectionStrings[databaseName];
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("Connected to {0}", databaseName);
}
}
catch (Exception ex)
{
// Handle the connection failure.
Console.WriteLine("FAILED to connect to {0} - {1}", databaseName, ex.Message);
}
}
// Wait for a keypress to stop the console closing.
Console.WriteLine("Press any key to finish.");
Console.ReadKey();
}
}
}
Look at the SqlConnection Class. It includes a basic sample. Just put a loop around that sample to connect to each server, and if any server fails to connect it throws an exception.
Then just set it up as a scheduled task in Windows.
A nice way to report the status might be with an email, which can easily be sent out with SmtpClient.Send (the link has a nice simple sample.
Why c#? You could make a simple batch file that does this using the osql command.
osql -S servername\dbname -E -Q "select 'itworks'"
You can also have a look at this method:
SqlDataSourceEnumerator.Instance.GetDataSources()
It gives you a list of SQL servers available on the network.
You know, they make monitoring tools that let you know if your sql server goes down . . .

Categories