I am trying to make some exception handling on the following code. Basically I want a MessageBox.Show("ErrorMessage") to show if the connection to the server can't be established.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
}
I have already tryed with
if (mongoServer.State == MongoServerState.Connected)
{
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
else
{
MessageBox.Show("Connection to MongoDB lost");
return null;
}
but that did not work since the state of the mongoServer first changes to connected in the query.
What should I do to make it work?
I feel stupid now :P
Using a simple try-catch worked.
public List<MongoDBModel> MongoDBModel
{
get
{
string connectionString = "mongodb://127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "TestPointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
try
{
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, MeterUID);
List<MongoDBModel> Cursor = mongodb.FindAs<MongoDBModel>(mongodbQuery).ToList();
return Cursor;
}
catch (MongoConnectionException e)
{
MessageBox.Show(e.Message);
return null;
}
}
}
Sorry for your troubles.
Related
`
using (var s = webRequest.GetResponse().GetResponseStream())
{
using (var sr = new StreamReader(s))
{
var entitydatafromMysql = sr.ReadToEnd();
string bsObj2 = string.Empty;
if (entitydatafromMysql.Contains("Success0:"))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(string));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(entitydatafromMysql)))
{
bsObj2 = (string)deserializer.ReadObject(ms);
bsObj2 = bsObj2.Remove(0, 9);
dtMySQLdata = (DataTable)JsonConvert.DeserializeObject(bsObj2, (typeof(DataTable)));
for (int i = 0; i < dtMySQLdata.Rows.Count; i++)
{
Entity entity = new Entity("efl_archivalemail");
entity["efl_archivalemailid"] = Convert.ToString(dtMySQLdata.Rows[i]["activityid"]);
entity.Id = new Guid(Convert.ToString(dtMySQLdata.Rows[i]["activityid"]));
entity["efl_name"] = Convert.ToString(dtMySQLdata.Rows[i]["sender"]);
entity["efl_description"] = Convert.ToString(dtMySQLdata.Rows[i]["description"]);
ec.Entities.Add(entity);
}
}
}
else
{
throw new InvalidPluginExecutionException(entitydatafromMysql);
}
}
}
`
This is a plugin code so I am using POST API to connect and get data FROM mysql database. I know I need to map CRM and Mysql entity attributes but I can only access CRM attributes by IserviceProviders execution context how can I do this?
I am trying to add an element in existing isolated folder in xml
code:
public void writeToXML(List<AppTile> appList)
{
// Write to the Isolated Storage
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!ISF.FileExists("config.xml"))
{
using (IsolatedStorageFileStream stream = ISF.OpenFile("config.xml", FileMode.CreateNew))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AppTile>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
serializer.Serialize(xmlWriter, appList);
}
stream.Close();
}
}
else
{
string tileName = null;
string url = null;
string key = null;
byte [] tilePic = null;
XDocument loadedData;
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
tilePic = app.TilePic;
// tilePic = Encoding.UTF8.GetString(app.TilePic,0,app.TilePic.Length);
// tilePic = Encoding.Unicode.GetString(app.TilePic,0,app.TilePic.Length);
// var writer = new BinaryWriter(tilePic);
}
using (Stream stream = ISF.OpenFile("config.xml", FileMode.Open, FileAccess.ReadWrite))
{
loadedData = XDocument.Load(stream);
var RootNode = new XElement("AppTile");
RootNode.Add(new XElement("TileName", tileName));
RootNode.Add(new XElement("Key", key));
RootNode.Add(new XElement("Url", url));
RootNode.Add(new XElement("TilePic", tilePic));
// Find Root Element And Descedents and Append New Node After That
var root = loadedData.Element("ArrayOfAppTile");
var rows = root.Descendants("AppTile");
var lastRow = rows.Last();
lastRow.AddAfterSelf(RootNode);
}
// Save To ISOconfig.xml File
using (IsolatedStorageFileStream newStream = new IsolatedStorageFileStream("config.xml", FileMode.Create, ISF))
{
loadedData.Save(newStream);
newStream.Close();
}
}
}
}
}
while reading from xml i am using xmlWriter and deserialize it to get List
when ever i am trying to acces the tilePic of AppTile type i am getting error :The component cannot be found. with the following code::
Image img = new Image();
MemoryStream imgStream = new MemoryStream(NewApp.TilePic);//NewApp is AppTile type
BitmapImage imgSource = new BitmapImage();
imgSource.SetSource(imgStream);//here i get error
img.Source = imgSource;
Its most likely with the TilePic i am saving is not formatted correctly to be retrieved.
Please Help!!
Why don't you use the SaveJpeg extension methodoogy in creating the byte array?
This one might help you!
Windows Phone - byte array to BitmapImage converter throws exception
solved the issue:
while saving the byte array it is encoded to some format not recognizable while reading,So what i have done is saved it as a string.So the updated code is:
else
{
string tileName = null;
string url = null;
string key = null;
string tilePicString = null;
XDocument loadedData;
System.Windows.Media.Imaging.BitmapImage imgSource = new System.Windows.Media.Imaging.BitmapImage();
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
//changed here
tilePicString = System.Convert.ToBase64String(app.TilePic);
}
//same code as above
Validation of the xml file against xsd from file location is working fine, but when we validate the xml against xsd from mysql location, it is not working.
this is channel
var SQLText = "";
var ResultSet = "";
var dbConn =GetCtDexConn();
function validateHL7Msg(incomingXml)
{
var validMessage = true;
var HL7xml = new XML(SerializerFactory.getSerializer('HL7V2').toXML(incomingXml));
logger.info('HL7xml '+HL7xml);
try
{
//SQLText = "select DEXPropXML from dbo.DEXUserProperties where Property = 'ClaimTrakValidationXml'";
SQLText = "select * from TestXML";
ResultSet = dbConn.executeCachedQuery(SQLText);
while (ResultSet.next()){
var clobdata = ResultSet.getClob(1);
var cloblength = clobdata.length();
var StringXML = clobdata.getSubString(1, cloblength);
var Validations = new XML(StringXML);
logger.info('Validations: '+Validations);
}
}
finally
{
dbConn.close();
}
var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
var schema = schemaFactory.newSchema(Validations);
for each(mshxml in HL7xml)
{
var reader = new Packages.java.io.StringReader(mshxml);
var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(reader);
// create a new validator for the schema
var validator = schema.newValidator();
try {
// validates the message
validator.validate(xmlFile);
// valid message
logger.info('valid');
} catch (err) {
// invalid message
logger.error(err.toString());
logger.info("error")
}
return validMessage;
}
}
/************Main Flow*****************/
var incomingXml = msg;
if(validateHL7Msg(incomingXml))
{
logger.info("message processed");
}
else
{
logger.info("message discarded");
}
I've implemented a simple chat application .But when client leaves the page or closes browser tab disconnect event is called many times. Some time twice some time thrice. Inside disconnect call back function i'm inserting chat history into database. As callback function is calling many times same chat history is inserting many times. Dont know what is the problem. Please help.
Code is like this
Server side code
var sys = require('sys');
var fs = require('fs');
var io = require('socket.io');
var connection = function(){
sys.puts("Here")
var mysql = require('mysql');
var sql = mysql.createConnection({
host:'localhost',
port:3306,
user:'root',
password:'root'
});
sql.query('use chat');
sys.puts("Here" +sql)
return sql;
}
var Server = require('http').createServer(function(req, response){
sys.puts("request recieved");
response.writeHeader(200,{"Content-Type":"text/html"});
response.write("Hello World");
var rs = fs.createReadStream(__dirname + '/chat.html')
sys.pump(rs,response);
});
var history = "";
var socket = io.listen(Server);
var mysql = connection();
socket.sockets.on('connection',function(client){
sys.puts("socket connected ID "+client.id);
sys.puts("session id",client.handshake.sessionID)
var username;
client.send('Welcome to chat');
client.send('Enter your name');
client.on('message',function(message){
if(!username)
{
username = message;
client.send('Welcome,' +username);
return;
}
feedback = username+' sent:'+message;
history = history + feedback + '\n';
client.send(feedback)
client.broadcast.send(feedback);
sys.puts("History is " +history);
sys.puts("mysql" +mysql);
client.on('disconnect',function(){
mysql.query('insert into tblchatHistory (fldChatHistory) values ("'+history+'")',function(err){
sys.puts("error" +err);
history = "";
})
sys.puts("socket connected ID "+client.id);
})
})
})
Server.listen(4000);
Client side code
<script type="text/javascript">
var socket;
socket = new io.connect("http://localhost:4000");
var connect = false;
socket.on('connect',function(){
alert("connected "+socket.socket.sessionid);
connect = true;
})
function chat()
{
socket.on('message',function(message){
var data = message;
var list ='<li>' +data +'</li>'
document.getElementById("log").innerHTML +=list;
})
}
function sendMsg(event)
{
var entry = document.getElementById("entry");
var msg = entry.value;
if(event.keyCode != 13)return
if(msg)
{
if(connect)
{
socket.emit('message',msg);
entry.value = "";
}
}
}
</script>
<body onload="chat();">
<h1>Chat</h1>
<div><ul id="log"></ul></div>
<div id="console">
<input type="text" id="entry" onkeypress="sendMsg(event);"/>
</div>
<div><a href="http://localhost:8085/BillDesk/welcomeJSF.jsf" >Exit chat</a></div>
</body>
I load label and icon from mysql database.
and i'd like to create a list with label and icon field.
So I try to do something like that but it doesn't work indeed each line contain label but icon is empty.
var xmllisteFamille:XMLList = XML(event.result).famille;
var xmlListCollFami = new XMLListCollection(xmllisteFamille);
for each (var item:Object in xmlListCollFami){
var vbox:VBox = new VBox;
vbox.label = item.sdfNom;
trace(vbox.label);
vbox.percentHeight=100;
vbox.percentWidth=100;
var xmlItem2:XMLList = item.commDent;
if(xmlItem2.length()>0){
/*
var listAcc:List = new List();
listAcc.percentHeight = 100;
listAcc.percentWidth =100;
listAcc.labelField = "name";
listAcc.dataProvider = xmlItem2;
vbox.addChild(listAcc);
accOnglet1.addChild(vbox); */
var urlImageRoot : urlManager = new urlManager();
var urlRootDental:String = urlImageRoot.urlDental();
trace(urlRootDental);
var list:Array = new Array();
var object:Object;
var xmlListdetail:XMLListCollection = new XMLListCollection(xmlItem2);
for each (var item2:Object in xmlListdetail)
{
object = new Object();
// -- --
object.label = item2.name;
var rootIcon:String= "http://127.0.0.1:10088/Sys/OEMySQL/Dental/"+item2.photo;
trace("rootIcon " + rootIcon);
object.icon = rootIcon;
trace("object.icon " + object.icon);
list.push(object);
}
/* var aNode:XML;
for each (aNode in xmlItem2)
{
object = new Object();
// -- --
object.label = aNode.name;
object.icon = new urlManager().urlDental()+aNode.photo;
list.push(object);
} */
var arrList:ArrayList;
arrList = new ArrayList(list);
var listAcc:List = new List();
listAcc.percentHeight = 100;
listAcc.percentWidth =100;
listAcc.labelField = "label";
listAcc.iconField="icon";
//listAcc.dataProvider = xmlItem2;
listAcc.dataProvider = arrList;
vbox.addChild(listAcc);
accOnglet1.addChild(vbox);
}
}
}
}
I hope that you can help me.
Thanks
it may be crossdomain issue
you need to know if flash player requires crossdomain.xml in this case
use charles proxy to check what exactly you are sending to server (request) and getting back from server (response)
charles proxy website
I found the solution.
I had to create an itemrenderer and add it in as3 to my list.
thanks