I am trying to insert data into database by using windows from application . I hosted it into console application . I am using .net remoting to invoke the method . My host is running without any problem and i also can run the windows form application without any problem . But problem is when i clicked the submit button to insert data i got error.I do not know why i am getting this error .
Exception thrown: 'System.NullReferenceException' in mscorlib.dll
Additional information: Object reference not set to an instance of an object. occurred
Here is the Interface .
namespace IHelloRemotingService
{
public interface IHelloRemotingService
{
void Insert(string Name, string Address, string Email, string Mobile)
}
}
Here is the Implementation of the interface ..
public class HelloRemotingService : MarshalByRefObject , IHelloRemotingService.IHelloRemotingService
{
public void Insert(string Name, string Address, string Email, string Mobile)
{
string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("AddNewStudent", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#EmailID", Email);
cmd.Parameters.AddWithValue("#Mobile", Mobile);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Code for Hosting service ....
namespace RemotingServiceHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" .NET Remoting Test Server");
Console.WriteLine(" *************************");
Console.WriteLine();
try
{
StartServer();
Console.WriteLine("Server started");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine("Server.Main exception: " + ex);
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
StopServer();
}
static void StartServer()
{
RegisterBinaryTCPServerChannel(500);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService.HelloRemotingService),
"Insert.rem",
WellKnownObjectMode.Singleton);
}
static void StopServer()
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch (Exception ex)
{
Console.WriteLine("Server.StopServer exception: " + ex);
}
}
}
static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
{
IServerChannelSinkProvider firstServerProvider;
IClientChannelSinkProvider firstClientProvider;
var channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = port;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Code for windows form application ..
namespace HelloRemotingServiceClient
{
public partial class InsertStudentData : Form
{
public InsertStudentData()
{
InitializeComponent();
RegisterBinaryTcpClientChannel();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
remService.Insert(textName.Text, textAddress.Text, textEmail.Text, textBox1.Text);
label5.Text = "Recored Inserted Successfully";
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RegisterBinaryTcpClientChannel(string name = "tcp client")
{
IClientChannelSinkProvider firstClientProvider;
IServerChannelSinkProvider firstServerProvider;
var channelProperties = new Hashtable();
channelProperties["name"] = name;
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = 0; // auto
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null);
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Design of the form ..
Here is the screen shot of errors messages .
The text boxes are able to catch the values but why its throwing this error ?
Here is a working project. You did not configure the formatter.
SharedLib Project:
namespace IHelloRemotingService
{
public interface IHelloRemotingService
{
void Insert(string Name, string Address, string Email, string Mobile);
}
}
Server Console Project:
namespace Server
{
public class HelloRemotingService : MarshalByRefObject, IHelloRemotingService.IHelloRemotingService
{
public HelloRemotingService()
{
}
public void Insert(string Name, string Address, string Email, string Mobile)
{
Console.WriteLine("HelloRemotingService.Insert called");
}
public override object InitializeLifetimeService()
{
return null; // manage lifetime by myself
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" .NET Remoting Test Server");
Console.WriteLine(" *************************");
Console.WriteLine();
try
{
StartServer();
Console.WriteLine("Server started");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine("Server.Main exception: " + ex);
}
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
StopServer();
}
static void StartServer()
{
RegisterBinaryTCPServerChannel(500);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService),
"Insert.rem",
WellKnownObjectMode.Singleton);
}
static void StopServer()
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch(Exception ex)
{
Console.WriteLine("Server.StopServer exception: " + ex);
}
}
}
static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
{
IServerChannelSinkProvider firstServerProvider;
IClientChannelSinkProvider firstClientProvider;
var channelProperties = new Hashtable();
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = port;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Client WinForms Project:
namespace Client
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
RegisterBinaryTcpClientChannel();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (MainForm form = new MainForm())
{
Application.Run(form);
}
}
/// <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)
{
foreach (IChannel channel in ChannelServices.RegisteredChannels)
{
try
{
ChannelServices.UnregisterChannel(channel);
}
catch (Exception ex)
{
Debug.WriteLine("Client.Dispose exception: " + ex);
}
}
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
private void _btnAccessServer_Click(object sender, EventArgs e)
{
try
{
var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
remService.Insert("MyName", "MyAddress", "MyEmail", "MyMobile");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RegisterBinaryTcpClientChannel(string name = "tcp client")
{
IClientChannelSinkProvider firstClientProvider;
IServerChannelSinkProvider firstServerProvider;
var channelProperties = new Hashtable();
channelProperties["name"] = name;
channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
channelProperties["machineName"] = Environment.MachineName;
channelProperties["port"] = 0; // auto
// create client format provider
var clientProperties = new Hashtable();
clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
firstClientProvider = clientFormatProvider;
// create server format provider
var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null);
serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
firstServerProvider = serverFormatProvider;
TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
ChannelServices.RegisterChannel(tcp, false);
}
}
}
Related
I am creating a multithread server and I am using mutex to control the sending data, the problem is when a client disconnect all the others clients also disconnect.
This is the server code
using Newtonsoft.Json;
using Pastel;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeepestSwordServer
{
public class Program
{
public static TcpListener server;
public static TcpClient client = new TcpClient();
public static Thread t;
public static Mutex mutex = new Mutex(false, "poligamerMod");
public static List<Connection> list = new List<Connection>();
public static Connection con;
static void Main(string[] args)
{
string ConfigPath = Path.Combine(Environment.CurrentDirectory, "config.json");
if (File.Exists(ConfigPath))
{
Console.WriteLine("Starting Server...".Pastel(Color.FromArgb(165, 229, 250)));
try
{
string json = File.ReadAllText(ConfigPath);
Config config = JsonConvert.DeserializeObject<Config>(json);
Start(config.Ip, config.Port);
}
catch (Exception e)
{
Console.WriteLine($"Failed To Start Server Error: {e.Message}".Pastel(Color.FromArgb(255, 0, 0)));
}
}
else
{
Console.WriteLine("Creating Config File...".Pastel(Color.FromArgb(165, 229, 250)));
Config config = new Config();
config.Ip = "0.0.0.0";
config.Port = 3878;
string json = JsonConvert.SerializeObject(config);
File.Create(ConfigPath).Dispose();
File.WriteAllText(ConfigPath, json);
Console.WriteLine("File Created!".Pastel(Color.FromArgb(58, 255, 0)));
Console.WriteLine("Please see the config.json where is the ip, port and password if needed of the server, you need to restart the server!".Pastel(Color.FromArgb(165, 229, 250)));
Console.ReadLine();
}
}
public static void Start(string ip, int port)
{
Console.WriteLine("Server Ready!".Pastel(Color.FromArgb(58, 255, 0)));
server = new TcpListener(IPAddress.Parse(ip), port);
server.Start();
while (true)
{
client = server.AcceptTcpClient();
con = new Connection();
con.stream = client.GetStream();
con.streamr = new StreamReader(con.stream);
con.streamw = new StreamWriter(con.stream);
con.username = con.streamr.ReadLine();
con.id = con.streamr.ReadLine();
Event #event = new Event();
#event.EventType = EventType.Join;
#event.Username = con.username;
#event.Id = con.id;
string join = JsonConvert.SerializeObject(#event);
foreach (Connection c in list)
{
c.streamw.WriteLine(join);
#event = new Event();
#event.EventType = EventType.Join;
#event.Username = c.username;
#event.Id = c.id;
string newJoin = JsonConvert.SerializeObject(#event);
con.streamw.WriteLine(newJoin);
}
list.Add(con);
#event = new Event();
#event.EventType = EventType.List;
foreach (Connection c in list.ToList())
{
#event.List.Add(c.username, c.id);
}
string playerList = JsonConvert.SerializeObject(#event);
con.streamw.WriteLine(playerList);
Console.WriteLine($"{con.username} with id {con.id} has connected!".Pastel(Color.FromArgb(58, 255, 0)));
t = new Thread(HearConnection);
t.Start();
}
}
public static void HearConnection()
{
Connection hcon = con;
do
{
try
{
foreach (Connection c in list.ToList())
{
mutex.WaitOne();
c.streamw.WriteLine(hcon.streamr.ReadLine());
mutex.ReleaseMutex();
}
}
catch (Exception e)
{
list.Remove(hcon);
Event #event = new Event();
#event.EventType = EventType.Leave;
#event.Username = con.username;
#event.Id = con.id;
string leave = JsonConvert.SerializeObject(#event);
foreach (Connection c in list)
{
c.streamw.WriteLine(leave);
}
Console.WriteLine($"{hcon.username} with id {hcon.id} has disconnected!".Pastel(Color.FromArgb(255, 0, 0)));
Console.WriteLine(e.ToString());
break;
}
} while (true);
}
public struct Connection
{
public NetworkStream stream;
public StreamWriter streamw;
public StreamReader streamr;
public string username;
public string id;
}
}
}
Here is the important parts of the client code
public void Connect()
{
MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Button>().enabled = false;
MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Connecting...";
try
{
client.Connect(IPAddress.Parse(Ip.GetComponent<InputField>().text), Convert.ToInt32(Port.GetComponent<InputField>().text));
if (client.Connected)
{
t = new Thread(Listen);
stream = client.GetStream();
streamw = new StreamWriter(stream);
streamr = new StreamReader(stream);
streamw.AutoFlush = true;
streamw.WriteLine(Username);
streamw.WriteLine(Id);
t.IsBackground = true;
t.Start();
StartCoroutine(Yes());
}
else
{
MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
StartCoroutine(No());
}
}
catch (Exception e)
{
Logger.LogInfo(e.Message);
MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
StartCoroutine(No());
}
}
public void Listen()
{
while (client.Connected)
{
try
{
string message = streamr.ReadLine();
DoEvent(message);
Logger.LogInfo(message);
}
catch(Exception e)
{
if (!client.Connected)
{
LostConnection = true;
}
else
{
Logger.LogError(e.ToString());
}
}
}
}
What I want is that the others clients dont disconnect if one client disconnect.
I am working in xamarin.forms. I want to create background service for Android.
My requirement is to track device location (Latitude, longitude, place name, Employee code) and inserted to the web server every after 5 min. After successful login, service has been started and for a particular employee, data is start inserting. Even if the app is closed still service should be running in background and data is keep inserting.
My code is
using Android.App;
using Android.Content;
using Android.Locations;
using Android.Net;
using Android.OS;
using HRMS;
using HRMS.Interface;
using HRMS.TableAttributes;
using Newtonsoft.Json;
using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Xml.Linq;
using Xamarin.Forms;
using static HRMS.ServiceLayer.ServiceClasses;
using HRMS.MenuController;
using HRMS.Droid;
using Android.Provider;
namespace SilverHRMS.Droid.Service
{
[Service]
public class GPSTrackingService : Android.App.Service
{
#region Private Variables
static readonly string TAG = "X:" + typeof(GPSTrackingService).Name;
static int TimerWait = 300000; //150000;//25000 25 Sec; // 10 min 600000 and 20 Min 1200000
Timer _timer;
readonly string logTag = "GPSTrackingService";
private string deviceId = "";
private string googleAPI = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
#endregion
/// <summary>
///
/// </summary>
/// <param name="intent"></param>
/// <param name="flags"></param>
/// <param name="startId"></param>
/// <returns></returns>
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
try
{
// Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
//_timer = new Timer(o => { Log.Debug(TAG, "Hello from GPSTrackingService. {0}", DateTime.UtcNow); GetCurrentLocation(); }, null, 0, TimerWait);
_timer = new Timer(o => { GetCurrentLocation(); }, null, 0, TimerWait);
//_timer = new Timer(o => { GetCurrentLocation(); }, null, 0, TimerWait);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
return StartCommandResult.Sticky;
}
/// <summary>
///
/// </summary>
/// <param name="intent"></param>
/// <returns></returns>
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
/// <summary>
/// On Destroy App
/// </summary>
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
//Log.Debug(logTag, "Service has been terminated");
}
/// <summary>
/// Get Current Location and Insert to DB
/// </summary>
public async void GetCurrentLocation()
{
try
{
string statusMessage = string.Empty;
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
//Log.Debug(TAG, " getting GPS connection...");
if (App.MyEmployeeId != null)
{
#region Check Internet Connection
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
#endregion
#region Check GPS Location Position and Emp Code
//LocationManager locationManager = (LocationManager)GetSystemService(LocationService);
bool isGPSOn = App.CheckGPSConnection();
Position position = null;
if (isGPSOn)
{
try
{
position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
}
catch (Exception)
{
position = null;
}
}
#endregion
#region Insert Location to Local DB or Server DB
//Device Has Internet Connection
if (isOnline)
{
#region Online Location Insert Direct to the Server Database
if (position != null)
{
List<GPSTrackingLocationClass> lcListOnline = new List<GPSTrackingLocationClass>();
GPSTrackingLocationClass objGPSTrack = new GPSTrackingLocationClass();
objGPSTrack.Latitude = position.Latitude;
objGPSTrack.Longitude = position.Longitude;
objGPSTrack.EmpCd = App.MyEmployeeId;
objGPSTrack.GPS_Track_DateTime = App.GetDateTime(DateTime.Now);
IDevice device = DependencyService.Get<IDevice>();
deviceId = device.GetIdentifier();
deviceId = deviceId.Replace("+", "%2B");
objGPSTrack.DeviceId = deviceId;
string url = string.Format(googleAPI, position.Latitude, position.Longitude);
try
{
XElement xml = XElement.Load(url);
if (xml.Element("status").Value == "OK")
{
objGPSTrack.PlaceName = xml.Element("result").Element("formatted_address").Value;
}
else
{
objGPSTrack.PlaceName = string.Empty;
}
}
catch (Exception ex)
{
}
lcListOnline.Add(objGPSTrack);
if (lcListOnline.Count > 0)
{
string jsonContentsOnline = JsonConvert.SerializeObject(lcListOnline);
var responseOnline = await HRMS.ServiceLayer.GetResponseFromWebService.GetResponsePostData<HRMS.ServiceLayer.ServiceClasses.RootObject>(HRMS.ServiceLayer.ServiceURL.PostGPSLocation, jsonContentsOnline);
if (responseOnline.Flag == true)
{
statusMessage = responseOnline.Message;
}
}
}
#endregion
#region Local Database Entries Insert to Server Database
List<LocationTracking> lcListOffline = SideMenu.repoLocation.GetAllLocationAsync();
if (lcListOffline != null)
{
if (lcListOffline.Count > 0)
{
ObservableCollection<LocationTracking> lvCollection = new ObservableCollection<LocationTracking>(lcListOffline);
List<GPSTrackingLocationClass> lcListGoingtoOnline = new List<GPSTrackingLocationClass>();
foreach (var item in lvCollection)
{
GPSTrackingLocationClass objGPSTrackOffline = new GPSTrackingLocationClass();
objGPSTrackOffline.Latitude = item.Latitude;
objGPSTrackOffline.Longitude = item.Longitude;
objGPSTrackOffline.EmpCd = item.EmpCd;
objGPSTrackOffline.GPS_Track_DateTime = item.GPS_Track_DateTime;
objGPSTrackOffline.DeviceId = item.DeviceID;
string urlAPI = string.Format(googleAPI, item.Latitude, item.Longitude);
try
{
XElement xmlURL = XElement.Load(urlAPI);
if (xmlURL.Element("status").Value == "OK")
{
objGPSTrackOffline.PlaceName = xmlURL.Element("result").Element("formatted_address").Value;
}
else
{
objGPSTrackOffline.PlaceName = string.Empty;
}
}
catch (Exception exe)
{
}
if (!string.IsNullOrEmpty(objGPSTrackOffline.PlaceName))
{
lcListGoingtoOnline.Add(objGPSTrackOffline);
}
}
if (lcListGoingtoOnline.Count == lvCollection.Count)
{
string jsonContentsOffline = JsonConvert.SerializeObject(lcListGoingtoOnline);
var responseOffline = await HRMS.ServiceLayer.GetResponseFromWebService.GetResponsePostData<HRMS.ServiceLayer.ServiceClasses.RootObject>(HRMS.ServiceLayer.ServiceURL.PostGPSLocation, jsonContentsOffline);
if (responseOffline.Flag == true)
{
statusMessage = responseOffline.Message;
SideMenu.repoLocation.RemoveLocationAsync();
}
}
}
}
#endregion
}
//Device Has No Internet Connection
else
{
try
{
if (position != null)
{
IDevice device = DependencyService.Get<IDevice>();
deviceId = device.GetIdentifier();
deviceId = deviceId.Replace("+", "%2B");
string newDate = App.GetDateTime(DateTime.Now);
SideMenu.repoLocation.AddNewLocationAsync(newDate, position.Latitude, position.Longitude, App.MyEmployeeId, deviceId, "--");
}
}
catch (Exception ex)
{
//Log.Debug(TAG, "Please turn on GPS in your headset");
}
}
#endregion
}
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
await fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
/// <summary>
/// Start Location Service
/// </summary>
public static void StartLocationService()
{
// Starting a service like this is blocking, so we want to do it on a background thread
//new Task(() =>
//{
// Start our main service
try
{
Intent intent = new Intent(Android.App.Application.Context, typeof(GPSTrackingService));
Android.App.Application.Context.StartService(intent);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
//}).Start();
}
/// <summary>
/// Start Location Service
/// </summary>
public static void StartApplication()
{
try
{
Intent start = new Intent(Android.App.Application.Context, typeof(MainActivity));
// my activity name is MainActivity replace it with yours
start.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.ApplicationContext.StartActivity(start);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
public static void SendEmail(string text)
{
var email = new Intent(Android.Content.Intent.ActionSend);
email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "pankit.patel#silvertouch.com" });
email.PutExtra(Android.Content.Intent.ExtraSubject, "Send Crash Report");
email.PutExtra(Android.Content.Intent.ExtraText, "Hello, " + text);
email.AddFlags(ActivityFlags.NewTask);
email.SetType("message/rfc822");
Android.App.Application.Context.ApplicationContext.StartActivity(email);
}
/// <summary>
/// Stop Location Service
/// </summary>
public static void StopLocationService()
{
// Check for nulls in case StartLocationService task has not yet completed.
//Log.Debug("App", "StopGPSTrackingService");
try
{
Intent intent = new Intent(Android.App.Application.Context, typeof(GPSTrackingService));
Android.App.Application.Context.StopService(intent);
}
catch (Exception ex)
{
var fileService = DependencyService.Get<ISaveException>();
fileService.SaveTextAsync(App.FileName, ex.StackTrace);
}
}
}
}
This service is only running when app is open (even in background) but if I close the app then service is automatically stop working. How to solve this issue? I have so many xamarin blogs regarding this topic but I din't get any workaround yet.
How to make background service that should be running even after app is close?
I have my data in DocumentDb.
I want to edit one field in all documents with Type == 8.
How I can do it?
Create console app for it
Use Azure Functions
I tried the second option and it not working.
public static void Run(string myQueueItem, dynamic inputDocument)
{
if(inputDocument.Type == 8) {
inputDocument.Entity.Discount.Name = inputDocument.Entity.Discount.Name + "smth";
}
}
Do you have any idea?
Below code seems naïve and RU-wasteful but will work.
DocumentClient _documentDbclient;
// Database configuration
static readonly string DocumentDbKeyConfig = "3dzS7T3a8lgEblkEnzSsdfasdfasf2omI1cp7==";
static readonly string DocumentDbEndPointConfig = "https://your-docdb.documents.azure.com:443/";
static readonly string DocumentDbDatabaseNameConfig = "your-database-name";
void Main()
{
string collectionName = "TestCollection";
Uri uri = UriFactory.CreateDocumentCollectionUri(DocumentDbDatabaseNameConfig, collectionName);
InitializeDocumentDbAsync(DocumentDbDatabaseNameConfig).ConfigureAwait(false);
createDocumentCollectionIfNotExistAsync(DocumentDbDatabaseNameConfig, collectionName).ConfigureAwait(false);
DocumentCollection collection = _documentDbclient.ReadDocumentCollectionAsync(uri).Result;
var query = _documentDbclient.CreateDocumentQuery(uri);
var queryList = query.ToList();
int index = 0;
int count = 50; // number of item to fetch at a time
while (true)
{
var result = queryList.Skip(index * count).Take(count);
if (!result.Any())
{
// end iterating.
return;
}
foreach (Document element in result)
{
JObject j = (dynamic)element;
if(j["Type"] != 8) continue;
j["YourProperty"] = "Some Value"; // edit value.
var upsertedResult = _documentDbclient.UpsertDocumentAsync(uri, j, null, true).Result;
}
++index;
}
}
public async Task InitializeDocumentDbAsync(string databaseName)
{
// Create a new instance of the DocumentClient
_documentDbclient = new DocumentClient(
new Uri(DocumentDbEndPointConfig), DocumentDbKeyConfig);
// Check if the database FamilyDB does not exist
try
{
await _documentDbclient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
}
catch (DocumentClientException de)
{
// If the database does not exist, create a new database
if (de.StatusCode == HttpStatusCode.NotFound)
{
await _documentDbclient.CreateDatabaseAsync(new Database { Id = databaseName });
}
else
{
throw;
}
}
catch (Exception e)
{
throw;
}
}
private async Task createDocumentCollectionIfNotExistAsync(string databaseName, string collectionName)
{
try
{
await
_documentDbclient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
}
catch (DocumentClientException de)
{
// not exist
throw;
}
catch (Exception e)
{
// do nothing.
}
}
I have created this class for work with my DB connection.
Applications works fine but one or two times in a day i get this errors.
Invalid operation, the connection is completed. when running query: (different queries)
or other times I received this error.
Value Timeout expired. The timeout period expired before completion of the operation or the server is not responding. This error has occurred while attempting to connect to the server Principal.
and rare errors:
Error at the transport level when receiving results from the server. (provider: Session Provider, error:? 19 - You can not use the connection nf sica) when running query
Thread aborted. when executing query:
ExecuteNonQuery requires an open and available Connection. The current state of the connection is closed. when running query
My db Class(resumed):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Web;
using System.IO;
namespace BBDD
{
public class clsBBDD
{
private string strConexion;
private int intTransaciones;
private SqlTransaction Transaccion;
private SqlConnection Conexion;
public clsBBDD(string ParamConexion)
{
strConexion = ParamConexion;
intTransaciones = 0;
}
public int Execute(string Sql)
{
return ExecutePrivado(Sql);
}
public int Execute(string Sql, bool Force)
{
return ExecutePrivado(Sql, Force);
}
private int ExecutePrivado(string Sql,bool Force = false)
{
int result = 0;
SqlCommand sentencia;
try
{
if (!Force && !Sql.ToUpper().Contains("WHERE") && !Sql.ToUpper().Contains("INSERT"))
{
throw new Exception("Sentencia Update o Delete sin WHERE");
}
if (intTransaciones > 0)
{
sentencia = new SqlCommand(Sql, Conexion, Transaccion);
}
else
{
abrirConexion();
sentencia = new SqlCommand(Sql, Conexion);
}
sentencia.CommandTimeout = 0;
result = sentencia.ExecuteNonQuery();
cerrarConexion();
}
catch (Exception e)
{
SendMailError(Sql, e);
result = 0;
}
return result;
}
public bool AbrirTrans()
{
try
{
intTransaciones += 1;
if (intTransaciones == 1)
{
abrirConexion();
Transaccion = Conexion.BeginTransaction();
}
}
catch (Exception e)
{
SendMailError("Error al abrir transacción", e);
return false;
}
return true;
}
public bool CerrarTrans(bool CommitTrans)
{
try
{
intTransaciones -= 1;
if (intTransaciones == 0)
{
if (CommitTrans)
{
Transaccion.Commit();
}
else
{
Transaccion.Rollback();
}
cerrarConexion();
}
}
catch (Exception e)
{
SendMailError("Error al cerrar transacción", e);
return false;
}
return true;
}
public object GetValue(string Sql)
{
object resultado = null;
try
{
SqlCommand sentencia = getCommand(Sql);
SqlDataReader reader = sentencia.ExecuteReader();
while (reader.Read())
{
resultado = reader[0];
}
reader.Close();
cerrarConexion();
}
catch (Exception e)
{
SendMailError(Sql, e);
resultado = null;
}
return resultado;
}
public DataRow GetValuesInRow(string sql)
{
DataRowCollection dsr;
DataRow result;
try
{
dsr = GetDSr(sql);
if (dsr.Count > 0)
{
result = dsr[0];
}
else
{
result = null;
}
}
catch (Exception e)
{
SendMailError(sql,e);
result = null;
}
return result;
}
public DataSet GetDS(string Sql)
{
DataSet result = new DataSet();
SqlDataAdapter adapter;
try
{
SqlCommand command = getCommand(Sql);
adapter = new SqlDataAdapter(command);
adapter.Fill(result);
cerrarConexion();
}
catch (Exception e)
{
SendMailError(Sql, e);
result = null;
}
return result;
}
public DataRowCollection GetDSr(string sql)
{
DataRowCollection result;
try
{
DataSet ds = GetDS(sql);
result = ds.Tables[0].Rows;
}
catch (Exception e)
{
SendMailError(sql, e);
result = null;
}
return result;
}
private void abrirConexion()
{
Conexion = new SqlConnection(strConexion);
if (Conexion.State == ConnectionState.Closed)
{
Conexion.Open();
}
}
private void cerrarConexion(bool Force = false)
{
try
{
if (intTransaciones == 0 && Conexion != null)
{
Conexion.Close();
}
}
catch
{
}
}
private SqlCommand getCommand(string Sql)
{
SqlCommand result;
if (intTransaciones == 0)
{
abrirConexion();
}
result = Conexion.CreateCommand();
if (intTransaciones > 0)
{
result.Transaction = Transaccion;
}
result.CommandText = Sql;
result.CommandTimeout = 0;
return result;
}
}
}
How I Initialize class:
public partial class frmBase : System.Web.UI.Page
{
protected clsBBDD BD;
protected void Page_Init(object sender, EventArgs e)
{
BD = new clsBBDD(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
clsBase.BD = BD;
}
}
All my webforms heritage from frmBase and all clases heritatge from clsBase
For use BD I call like this:
string sql;
DataRowCollection DSTrabajos;
sql = "UPDATE tabletest SET validacion = '" + ValidacionText + "', ModificadoPor = '" + Username + "' WHERE referencia = " + ReferenciaID;
BD.Execute(sql);
sql = "SELECT orderID FROM TrabajosINBOX where referencia = " + ReferenciaID;
DSTrabajos = BD.GetDSr(sql);
foreach (DataRow r in DSTrabajos)
{
//more code inside
}
My connection string params
Data Source=ServerIP;Initial Catalog=BBDDNAME;User ID=USER;Password=***********;Max Pool Size=500;MultipleActiveResultSets=true
I get this error when I try to connect an # IP (local).
Its a socket (tcp & udp).
I use an emulator
If there is a code to activate WiFi on WP7 emulator??
or maybe I deactivate WiFi coonnection
this all my code to add a connection to can use it
private void AddComputer_Click(object sender, RoutedEventArgs e)
{
IPAddress iPAddress;
if (!IPAddress.TryParse(this.IPAddressTextBox.Text, out iPAddress))
{
MessageBox.Show("Error: Invalid IP Address is empty");
return;
}
this.ipAddressToAdd = iPAddress;
this.progressBar.IsIndeterminate = true;
this.StatusTextBlock.Visibility=(Visibility)0;
this.ContentPanel.Visibility=(Visibility)1;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.AddComputerThread), new NetworkHandler.DiscoveredServer("", this.ipAddressToAdd, false, "", this.checkBoxPassword.IsChecked.Value, this.passwordBox1.Password, NetworkHandler.NetworkCategory.Unknown));
}
private void AddComputerThread(object obj)
{
NetworkHandler.DiscoveredServer info = (NetworkHandler.DiscoveredServer)obj;
NetworkHandlerCommon.ConnectResult connectResult = ConnectionHandler.ConnectToComputer(info, true, MyApp.MajorVersion, MyApp.MinorVersion);
base.Dispatcher.BeginInvoke(delegate
{
this.AddComputerDispatcher(connectResult);
}
);
}
private void AddComputerDispatcher(NetworkHandlerCommon.ConnectResult connectResult)
{
this.progressBar.IsIndeterminate = false;
this.StatusTextBlock.Visibility=(Visibility)1;
this.ContentPanel.Visibility=(Visibility)0;
if (connectResult == NetworkHandlerCommon.ConnectResult.Connected)
{
base.NavigationService.Navigate(MyApp.HomePage());
return;
}
this.ShowConnectError(connectResult);
}
private void ShowConnectError(NetworkHandlerCommon.ConnectResult result)
{
switch (result)
{
case NetworkHandlerCommon.ConnectResult.UpdateServer:
ErrorHandler.ShowErrorMessage(1003);
return;
case NetworkHandlerCommon.ConnectResult.UpdateClient:
ErrorHandler.ShowErrorMessage(1002);
return;
case NetworkHandlerCommon.ConnectResult.Failed:
ErrorHandler.ShowErrorMessage(1005);
return;
case NetworkHandlerCommon.ConnectResult.AuthenticationFailure:
MessageBox.Show("Error: Password is incorrect.");
return;
case NetworkHandlerCommon.ConnectResult.NetworkNotConnected:
MainPage.ShowNetworkDisconnectedMessage();
return;
default:
return;
}
}
and this class is showing the error that it will happen if true
public class ErrorHandler
{
private class ErrorInfo
{
public string ErrorMessage
{
get;
set;
}
public string ErrorURL
{
get;
set;
}
public ErrorInfo(string errorMessage, string errorURL)
{
this.ErrorMessage = errorMessage;
this.ErrorURL = errorURL;
}
}
private static Dictionary<int, ErrorHandler.ErrorInfo> errorMapping;
static ErrorHandler()
{
ErrorHandler.errorMapping = new Dictionary<int, ErrorHandler.ErrorInfo>();
ErrorHandler.errorMapping.Add(1000, new ErrorHandler.ErrorInfo("Error 1000: We have detected that WiFi is NOT turned-on at your phone.", "http://wp.me/p1ZVRQ-w"));
ErrorHandler.errorMapping.Add(1001, new ErrorHandler.ErrorInfo("Error 1001: Password is incorrect.", "http://wp.me/p1ZVRQ-E"));
ErrorHandler.errorMapping.Add(1002, new ErrorHandler.ErrorInfo("Error 1002: Older version of application is running. Update application from Marketplace.", "http://wp.me/p1ZVRQ-H"));
ErrorHandler.errorMapping.Add(1003, new ErrorHandler.ErrorInfo("Error 1003: Older version of PC Remote server is running at PC", "http://wp.me/p1ZVRQ-K"));
ErrorHandler.errorMapping.Add(1004, new ErrorHandler.ErrorInfo("Error 1004: Computer is connected to a public network", "http://wp.me/p1ZVRQ-d"));
ErrorHandler.errorMapping.Add(1005, new ErrorHandler.ErrorInfo("Error 1005: Failed connecting to your PC", "http://wp.me/p1ZVRQ-j"));
ErrorHandler.errorMapping.Add(1006, new ErrorHandler.ErrorInfo("Error 1006: Could not wake up your computer", "http://wp.me/p1ZVRQ-S"));
ErrorHandler.errorMapping.Add(1007, new ErrorHandler.ErrorInfo("Error 1007: Unable to resume the app.", "http://wp.me/p1ZVRQ-W"));
}
public static void ShowErrorMessage(int errorId)
{
if (ErrorHandler.errorMapping.ContainsKey(errorId))
{
ErrorHandler.ErrorInfo errorInfo = ErrorHandler.errorMapping[errorId];
string text = errorInfo.ErrorMessage + Environment.NewLine + Environment.NewLine + "Need help troubleshooting this? ";
if (MessageBox.Show(text, "Error", MessageBoxButton.OKCancel).Equals(1))
{
MyApp.GoToWebURL(errorInfo.ErrorURL);
}
}
}
}