I'm following this example, ClientMongo to connect a WPF application to my MongoDB database via the connection string. But I get an error on the MongoClient when I call the GetServer method. The error states that GetServer doesn't exist, although the correct using references and usings have been added.
Can anyone spot if I've missed a step in setting this up? Or is there an alternative solution to create a connection with the remote DB?
This is the code I've used to connect, similar to the example above. The user and password have been starred out for privacy:
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDBApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string connectionString = "mongodb://<brian****>:<********123;>#ds048878.mongolab.com:48878/orders";
public MainWindow()
{
InitializeComponent();
var mongoUrl = MongoUrl.Create(connectionString);
var server = new MongoClient(connectionString).GetServer();
return server.GetDatabase(mongoUrl.DatabaseName);
}
}
}
If you are using the 2.x Version of the C# driver, forget about the Server object.
You can get your Database directly from the client:
var client = new MongoClient("<connectionString>");
return this.Client.GetDatabase("<databaseName>");
Related
I am new to C# and Serverless development. I am trying to create an AWS Lambda that has an API Gateway trigger. When the Lambda triggers I want to write a User record to the database.
Lambda:
namespace CreateProfile;
using System.Net;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Database;
using Users.Models;
public class Function
{
/// <summary>
/// This Lambda function is for creating a user profile
/// </summary>
public APIGatewayHttpApiV2ProxyResponse FunctionHandler(User user, ILambdaContext context)
{
LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
LambdaLogger.Log($"Payload Received: {user}");
// 1. Populate the relevant table(s) from our input
using myDbContext ctx = new();
ctx.Users.Add(user);
ctx.SaveChanges();
APIGatewayHttpApiV2ProxyResponse response = new ()
{
StatusCode = (int)HttpStatusCode.OK,
Body = "Great Scott...it worked!",
Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
};
return response;
}
}
I am using the following Assembly:
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(
DefaultLambdaJsonSerializer
))]
I am using the following as my database context:
namespace Database;
using Users.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Npgsql;
[DbConfigurationType(typeof(Config))]
public class MyDbContext: DbContext
{
public myDbContext(): base(MakeConnString()) {}
private static string MakeConnString()
{
// Will be moving these to a common location
string OptEnv(string key, string default_) =>
Environment.GetEnvironmentVariable(key) ?? default_;
string Env(string key) =>
Environment.GetEnvironmentVariable(key) ?? throw new MissingFieldException(key);
NpgsqlConnectionStringBuilder builder = new()
{
Host = Env("PGHOST"),
Port = int.Parse(OptEnv("PGPORT", "5432")),
SslMode = Enum.Parse<SslMode>(OptEnv("PGSSLMODE", "Require")),
TrustServerCertificate = true,
Database = OptEnv("PGDATABASE", "postgres"),
Username = OptEnv("PGUSER", "postgres"),
Password = Env("PGPASSWORD")
};
return builder.ConnectionString;
}
public DbSet<User> Users { get; set; }
}
When running this my Lambda hangs and I can't figure out why.
I'm assuming the database you are trying to interact with is an RDS instance or running on an EC2 instance in the same account, right?
If so, are your Lambda function deployed into your VPC? If not, the Lambda needs to be in order to talk to a VPC resource. The default is the Lambdas are NOT deployed in your VPC.
If you are using Serverless Framework then you need to add the following config to the provider section of your serverless.yml [https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml]
provider:
# Optional VPC settings
# If you use VPC then both securityGroupIds and subnetIds are required
vpc:
securityGroupIds:
- securityGroupId1
subnetIds:
- subnetId1
- subnetId2
The subnets you reference need to have a route to the subnets your database is provisioned into. They can be in the same subnets as the ones your RDS instance or EC2 is running the in DB.
Lastly, you need to ensure that the Security Group allows outbound traffic on the correct port for your Lambda Security Group, as well as, ensure that the Security Group on your database (EC2 or RDS) allows traffic from either the Lambda SG or the CIDR/IP ranges of the subnets you are deploying the Lambdas into on the correct port #.
The hanging is typically the request not making it to the DB - if you are already set up with your Lambda deployed in your VPC, then you should check the routing and Security Groups mentioned.
I have a file "20181023151311-book + notes.txt" stored in an application hosted in IIS server inside a folder named as "MyFiles" and I have to pull the file in a WPF application. I am using WebClient to download the file from the server but it is giving me an error
The remote server returned an error: (404) Not Found.
I tried to use System.Web.HttpUtitility.UrlEncode but still I am getting an error. Here is the code I used to pull the file from the server. The code runs perfectly if there are no special characters. Could you please help to solve the issue? Thanks!
using System.Windows;
namespace WebClientDownloadDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DownloadFile(#"https://localhost:40120/MyFiles/20181023151311-book + notes.txt");
}
public void DownloadFile(string fileUrl)
{
using (var client = new System.Net.WebClient())
{
var fileName = fileUrl.Substring(fileUrl.LastIndexOf(#"/") + 1);
client.DownloadFile(fileUrl, System.IO.Path.Combine("C:\\Users\\Username\\Downloads", fileName));
}
}
}
}
I just don't know how to explain this clearly. So I create a simple image pattern of what I did.
My question is, how would I be able to access my database in other class in LS?
I've been searching on net, but I didn't found any solution. I hope I'll find it here.
Thanks!.
Any suggestion is already appreciated.
Thanks for the answer Bryan, but I found the answer on my problem here Richard Waddell
Here is what I did to achieve my goal.
Switch your LS project to file view
Go to "Common" project, under "UserCode" folder, create a class (e.g. Authenticate.cs) and put this codes.
The code follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
namespace LightSwitchApplication
{
public class Authenticate
{
public static adminuser GetCurrentUser()
{
adminuser userFound = (from useritem in
Application.Current.CreateDataWorkspace().basecampcoreData.adminusers
where useritem.LoginID == Application.Current.User.Name
select useritem).SingleOrDefault();
if (userFound != null)
return userFound;
else
return null;
}
}
}
Then you can now call the Authenticate.GetCurrentUser() anywhere in the project.
Thanks!
The main difference is the first set of code that works is running inside a screen. For your Authenticate class, you need to do the following steps to access the Database.
Note: I'm assuming that your datasource has the default name of ApplicationData since you hid the name, if not, make the corresponding changes. If it's a completely different datasource, change "_IntrinsicData" in the steps below)
These steps are taken from the Lightswitch Help Website
Navigate to ..ServerGenerated\GeneratedArtifacts (in the LightSwitch project) and click on ApplicationData.cs and Add As Link.
Add the following code below, this code dynamically creates a connection to the database. LightSwitch uses “_IntrinsicData” as it’s connection string.
private ApplicationDataObjectContext m_context;
public ApplicationDataObjectContext Context
{
get
{
if (this.m_context == null)
{
string connString =
System.Web.Configuration.WebConfigurationManager
.ConnectionStrings["_IntrinsicData"].ConnectionString;
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata =
"res://*/ApplicationData.csdl|res://*/ApplicationData.ssdl|res://*/ApplicationData.msl";
builder.Provider =
"System.Data.SqlClient";
builder.ProviderConnectionString = connString;
this.m_context = new ApplicationDataObjectContext(builder.ConnectionString);
}
return this.m_context;
}
}
You should be able to access it through Context.adminusers
I'm in need to create an GPRS connection in an PDA that has windows ce 6. Now normally i would had to use the manufacturer's dll to create that, but they said that they use ras to accomplish this. The only problem of using that is that i program in .net c#, and the library is an unmanaged code one.
Fortunately i came by the opennetcf ras library that does already the necessary pInvokes for the windows ras library, the only problem being the poor documentation.
I created then an library that would call and set-up the necessary GPRS connection on windows. I'm using an Portuguese telecom operator that uses the following definitions:
Operator Name: Optimus P
Apn: umts
Password: *******
User: ******
Consulting the gsm module definition, i had the following modem settings:
Connection Name: GPRS
Device: Hayes Compatible on COM1:
Baund Rate:115200
Data Bits: 8
Parity:1
Stop Bits: 1
Flow Control: Hardware
and of course the extra settings (or how i call it the atCall)
+cgdcont=1, "ip", "umts"
This settings when i use the control panel and do an connect with that profile, it connects and i'm able to call all the webservices without an error. It also shows an extra profile for the modem that shows the settings for the device, incluid the ipaddress, subnet mask and even the default gateway.
The problem is that when i use the library that i created to create an gprs connection programatically, and then call the webservices at some point it throws me an web exception : The remote name could not be resolved. I also checked and the extra icon does not appear, but if i see the GPRS status it appears as it is connected.
The code that create, destroys and query if it exists an connection is as follows:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Net;
using OpenNETCF.Diagnostics;
namespace gsmAdapterNet
{
/// <summary>
/// GPRS Connection class
/// </summary>
public class GPRS
{
private static string connectionName = "GPRS";
/// <summary>
/// Connects the GPRS.
/// </summary>
/// <returns></returns>
public static bool ConnectGPRS()
{
//precisamos de obter as connecoes e ligar
RasEntryCollection connecoesPossiveis = Ras.Entries;
RasEntry _currentEntry = connecoesPossiveis[connectionName];
_currentEntry.RasStatus += new RasNotificationHandler(RasStatusHandler);
RasError resultado = _currentEntry.Dial(false);
if (resultado == RasError.Success)
return true;
else
return false;
}
static void RasStatusHandler(int hConn, RasConnState State, RasError ErrorCode)
{
Logger.WriteLine("");
Logger.WriteLine("RAS STATUS: " + ErrorCode.ToString() + " , State: " + State.ToString());
}
/// <summary>
/// Disconnects the GPRS.
/// </summary>
/// <returns></returns>
public static void DisconnectGPRS()
{
RasEntryCollection entradas = Ras.Entries;
foreach (RasEntry possivelEntrada in entradas)
{
if (possivelEntrada.Name == connectionName)
{
possivelEntrada.Hangup();
}
}
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public static bool isConnected()
{
RasConnection[] conecoes = Ras.ActiveConnections;
foreach (RasConnection conecao in conecoes)
{
if (conecao.Name == connectionName)
return true;
}
return false;
}
/// <summary>
/// Dumps the ras entries.
/// </summary>
public static void DumpRasEntries()
{
foreach (RasEntry entry in Ras.Entries)
{
Logger.DumpRasEntry(entry);
}
}
}
}
So resuming the question is how i can create an viable connection with the opennetcf ras library
Best Greetings
It seems as if the network interface for the GPRS connection that you get when dialing in is not configured with the correct DNS servers. Alternatively, the domain names needed for your service calls may be wrong.
To verify this:
Is it only a specific web service whose domain name cannot be resolved? Is it always the same? Do others work? Can you simply HTTP GET something like http://stackoverflow.com programmatically after the connection has been established?
how do we process a cube or access OLAP database through ASP.Net with C# code? what is the component to be used, in C#.Net for connecting OLAP database or process actions in anaysis Services ?
For processing, use Microsoft.AnalysisServices library, example code looks like:
Server server = new Server();
server.Connect(cubeConnectionString);
Database database = server.Databases.FindByName(databaseName);
Cube cube = database.Cubes.FindByName(cubeName);
cube.Process(ProcessType.ProcessFull);
For querying, use Microsoft.AnalysisServices.AdomdClient library, example code looks like:
using (Adomd.AdomdConnection adomdConnection = new Microsoft.AnalysisServices.AdomdClient.AdomdConnection())
{
adomdConnection.ConnectionString = cubeConnectionString;
Adomd.AdomdCommand adomdCommand = new Microsoft.AnalysisServices.AdomdClient.AdomdCommand();
adomdCommand.Connection = adomdConnection;
adomdCommand.CommandText = mdxQuery;
adomdConnection.Open();
cellSet = adomdCommand.ExecuteCellSet();
adomdConnection.Close();
}
Note that the two namespaces overlap, so you may need to alias if you use them in the same place.
http://msdn.microsoft.com/en-US/library/ms124924(v=SQL.90).aspx
http://msdn.microsoft.com/en-us/library/ms123483(v=SQL.90).aspx
You must process the database, not the cube. Because the cube has only the measures not the dimensions inside. This can give some conflicts.
To Prozess all, Cubes and Dimensions you must process the whole database:
Server server = new Server();
server.Connect(cubeConnectionString);
Database database = server.Databases.FindByName(databaseName);
database.Process(ProcessType.ProcessFull);
Answer for this already shared above but just sharing that I too had used the same Microsoft.AnalysisServices by API referring the sample project downloaded from my blog post to process cube from C# but when the dimension data gets changed then you need to process the database rather cube.
Also you can use EffectiveUserName property of connection string when an end user identity must be impersonated on the server.
NOTE: To use EffectiveUserName property, the caller must have administrative permissions in Analysis Services.
This example was done with Visual Studio Express 2012 and $44 copy of Ms SQL 2012 (God bless Microsoft for providing so much functionality for so little money). The OS was Win 8 pro.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//the next 2 using's had to be downloaded and "Add Reference"d for Visual Studio Express 2012
using Microsoft.AnalysisServices;
using Microsoft.AnalysisServices.AdomdClient;
using System.Windows.Forms;
using System;
using System.Data;
using System.Drawing;
namespace SSASDataview
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void RunSSAS(object sender, EventArgs e)
{
//i don't think Dataset is in the Analysis Services directives
DataSet ds = new DataSet();
// provider is the constant olap. datasource is the same server name you provide for Mgmt Studio or localhost
// initial catalog is tricky and important. It is not a standard ms sql database you see in Management Studio,
// even if your cube was create with tables from a particular database.
// the only place I was able to see "initial catalog" value was a File -> Open -> Analysis Services Database in 2012 Management Studio
// it was also the name of the VS2010 solution I used to create the cube.
AdomdConnection myconnect = new AdomdConnection(#"provider=olap;initial catalog=GLCubeThree;datasource=localhost");
AdomdDataAdapter mycommand = new AdomdDataAdapter();
mycommand.SelectCommand = new AdomdCommand();
mycommand.SelectCommand.Connection = myconnect;
// this query was created by the "Browser" you see for an Analysis Services project
// if you poke around the icons on the browser table the Design Mode icon will give you the cube query
// I think it's an MDX query, threre are also xml queries you can run with adomd
mycommand.SelectCommand.CommandText = "SELECT NON EMPTY { [Measures].[Per Balance] } ON COLUMNS, NON EMPTY { ([Gltime].[Fisc Per].[Fisc Per].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( { [Gltime].[Fisc Per].&[201301], [Gltime].[Fisc Per].&[201302], [Gltime].[Fisc Per].&[201307] } ) ON COLUMNS FROM [GL Cube]) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS";
myconnect.Open();
mycommand.Fill(ds, "tbl");
myconnect.Close();
// the below assigns the results of the cube query to a dataGridView
// if you drag a dataGridView control to your pallete it will create exactly
// what you need for the line below to work.
// your project type has to be a Window Forms Applications
// this code shown here is in the default Form1.Designer.cs not Form1.cs
dataGridView1.DataSource = new DataView(ds.Tables[0]);
}
private void Quit_Click(object sender, EventArgs e)
{
this.Close();
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Button runssas;
private System.Windows.Forms.Button quit;
}
}