Thanks in advance!!! While run the windows service it shows the error like cannot start service from command line or a debugger. a windows service must first be installed(using installutil.exe) and then started with the server explorer, windows services administrative tool or net start command. But I have installed the installutil.exe after that also the same error occurs..In Task Manager the service running but while debug the code its not working.
What I have tried:
Program.cs
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceTest()
};
ServiceBase.Run(ServicesToRun);
The Problem occurs in this line...
<servicestorun =="" new="" servicebase[]
="" {
="" servicetest()
="" };
service="" test:
using="" system;
using="" system.collections.generic;
using="" system.componentmodel;
using="" system.data;
using="" system.diagnostics;
using="" system.linq;
using="" system.serviceprocess;
using="" system.text;
using="" system.io;
using="" system.timers;
using="" system.net;
using="" system.data.common;
using="" system.configuration;
using="" system.web.script.serialization;
namespace="" windowsservicetest
{
=""
="" public="" partial="" class="" servicetest="" :="" servicebase
="" initializecomponent();
="" }
="" timer="" timer();
="" initialize="" the="" timer
="" this="" method="" is="" used="" to="" raise="" event="" during="" start="" of="" service
="" void="" ondebug()
="" onstart(null);
="" protected="" override="" onstart(string[]="" args)
="" try
="" {
="" add="" line="" text="" file="" service
="" exceptionstring("synchronization="" started");
="" handle="" elapsed="" event
="" timer.elapsed="" +="new" elapsedeventhandler(onelapsedtime);
="" statement="" set="" interval="" 1="" minute="" (="60,000" milliseconds)
="" timer.interval="Double.Parse(ConfigurationManager.AppSettings["Interval"].ToString());
" enabling="" timer
="" timer.enabled="true;
" catch="" (exception="" ex)
="" exceptionstring(ex.tostring());
="" stop="" onstop()
="" {
="" stopped");
="" }
="" private="" onelapsedtime(object="" source,="" elapsedeventargs="" e)
="" foreach="" (connectionstringsettings="" css="" in="" configurationmanager.connectionstrings)
="" string="" name="css.Name;
" connstring="css.ConnectionString;
" provider="css.ProviderName;
" if="" (name.contains("constr")="" &&="" !="" )
="" traceservice("synchronization="" starts="" at="" "="" datetime.now,="" connstring);
="" }
="" }
="" exceptionstring(string="" content)
="" up="" a="" filestream
="" filestream="" fs="new" filestream(@"c:\\log.txt",="" filemode.openorcreate,="" fileaccess.write);
="" streamwriter="" for="" adding="" text
="" sw="new" streamwriter(fs);
="" find="" end="" underlying="" sw.basestream.seek(0,="" seekorigin.end);
="" sw.writeline("testing"="" content);
="" filestream
="" sw.flush();
="" close="" writer
="" sw.close();
="" traceservice(string="" content,="" connectionstring)
="" sw.writeline(content);
="" sw.close();
="" constrfromwebconfig="connectionstring;
" dbconnection="" conn="GetDBConnection.CreateDbConnection(constrfromWebConfig);
" dbcommand="" command="conn.CreateCommand();
" command.commandtype="CommandType.StoredProcedure;
" command.commandtext="Proc_SelectFirebaseMessageByStatus" ;
="" (conn.state="=" connectionstate.closed)
="" conn.open();
="" getdbconnection.addparameterwithvalue(command,="" "@interviewer",="" interviewer);
="" getdbconnection.addpara="" meterwithvalue(command,="" "@language",="" language);
="" customdataadapter="" da="new" customdataadapter();
="" datatable="" dt="new" datatable();
="" da.selectcommand="command;
" da.fill(dt);
="" (dt.rows.count=""> 0)
{
foreach (DataRow row in dt.Rows)
{
string msgtitle = row[0].ToString();
string msgcontent = row[1].ToString();
string firebaseid = row[2].ToString();
string Userid = row[3].ToString();
string MessageID = row[4].ToString();
string includeimage = row[5].ToString();
//string imageurl = row[14].ToString();
string msgstatus = row[6].ToString();
string usermobile = row[7].ToString();
if (usermobile == "ANDROID")
firebasemessage_notification(firebaseid, msgtitle, msgcontent);
// SendNotification("d-MHnIPkTXuTlnUm3he96E:APA91bE_5r5Q9eC2KVTzKeg2AC1vuYA9qpxVqk2UQ27TwS66LmI4Gnr4d26rXGC6b1947ncpddvNF0SBeQKOeGawh9uteGUPOmmQDbUjHHVpfJDi2HJKU2WZD5YHQZu7p5_jM4_8qK0O", "Hai");
else
firebasemessage_notificationIOS(firebaseid, msgtitle, msgcontent);
command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Proc_UpdateFirebaseMessageStatus";
GetDBConnection.AddParameterWithValue(command, "@UserId", Userid);
GetDBConnection.AddParameterWithValue(command, "@MsgId", MessageID);
GetDBConnection.AddParameterWithValue(command, "@MsgStatus", "SENT");
command.ExecuteNonQuery();
}
}
TraceServiceAdditionNotification("Addition Synchronization starts at " + DateTime.Now, connectionstring);
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
}
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
}
}
private void TraceServiceAdditionNotification(string content, string connectionstring)
{
try
{
//set up a filestream
//FileStream fs = new FileStream(@"C:\\log.txt", FileMode.OpenOrCreate, FileAccess.Write);
////set up a streamwriter for adding text
//StreamWriter sw = new StreamWriter(fs);
////find the end of the underlying filestream
//sw.BaseStream.Seek(0, SeekOrigin.End);
////add the text
//sw.WriteLine(content);
////add the text to the underlying filestream
//sw.Flush();
////close the writer
//sw.Close();
try
{
string constrfromWebConfig = connectionstring;//ConfigurationManager.AppSettings["ConStr"].ToString();
DbConnection conn = GetDBConnection.CreateDbConnection(constrfromWebConfig);
DbCommand command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "ProcSelecttNotification";
if (conn.State == ConnectionState.Closed)
conn.Open();
GetDBConnection.AddParameterWithValue(command, "@MobileStatus", "NO");
// GetDBConnection.AddParameterWithValue(command, "@Language", Language);
CustomDataAdapter da = new CustomDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = command;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string ID = row[0].ToString();
string Userid = row[1].ToString();
string Notifierid = row[5].ToString();
string msgtitle = row[3].ToString();
string msgcontent = row[4].ToString();
string firebaseid = row[10].ToString();
string msgstatus = row[9].ToString();
string mobile = row[12].ToString();
if (mobile == "ANDROID")
firebasemessage_notification(firebaseid, msgtitle, msgcontent);
else
firebasemessage_notificationIOS(firebaseid, msgtitle, msgcontent);
command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "ProcUpdateNotification";
GetDBConnection.AddParameterWithValue(command, "@id", ID);
GetDBConnection.AddParameterWithValue(command, "@MobileStatus", "YES");
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
}
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
}
}
public string SendNotification(string deviceId, string message)
{
string GoogleAppID = "AAAA7Ss7aE4:APA91bEdk8cKA6igSh2Ol4rJ2Z99NjBJkpJlAnDcB_T8ArdBj_9h5fs-NQCRtueKIkcIPmfne-T5hv-fV7wgV1io5n9fLgAMEVt59HT4tF1A04r_SUYhSaILIdq9_eMrX48qe_Kqb7oU";//"AIzaSyDCSbNzV7kDrivcz7rcuj8sQdxmmq9jvgM";
var SENDER_ID = "1018632562766";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https:
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
public bool firebasemessage_notification(string deviceid, string messagetitle, string messagecontent)
{
try
{
var applicationID = "AAAA7Ss7aE4:APA91bEdk8cKA6igSh2Ol4rJ2Z99NjBJkpJlAnDcB_T8ArdBj_9h5fs-NQCRtueKIkcIPmfne-T5hv-fV7wgV1io5n9fLgAMEVt59HT4tF1A04r_SUYhSaILIdq9_eMrX48qe_Kqb7oU";
var senderId = "1018632562766";
string deviceId = deviceid;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
data = new
{
body = messagecontent,
title = messagetitle,
icon = "ic_launcher",
}
,
notification = new
{
body = messagecontent,
title = messagetitle,
content_available = true
}
};
string postData = "{ " +
" \"to\" : " + deviceId +
" \"data\" : { \"message\" : " + messagecontent + ", \"time\": " + "\"" + System.DateTime.Now.ToString() + "\"} " +
" }";
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
return true;
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
string str = ex.Message;
return false;
}
}
public bool firebasemessage_notificationIOS(string deviceid, string messagetitle, string messagecontent)
{
try
{
var applicationID = "AAAA7Ss7aE4:APA91bEdk8cKA6igSh2Ol4rJ2Z99NjBJkpJlAnDcB_T8ArdBj_9h5fs-NQCRtueKIkcIPmfne-T5hv-fV7wgV1io5n9fLgAMEVt59HT4tF1A04r_SUYhSaILIdq9_eMrX48qe_Kqb7oU";
var senderId = "1018632562766";
string deviceId = deviceid;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
data = new
{
body = messagecontent,
title = messagetitle,
icon = "ic_launcher",
},
notification = new
{
body = messagecontent,
title = messagetitle,
content_available = true
}
};
string postData = "{ " +
" \"to\" : " + deviceId +
" \"data\" : { \"message\" : " + messagecontent + ", \"time\": " + "\"" + System.DateTime.Now.ToString() + "\"} " +
" }";
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
return true;
}
catch (Exception ex)
{
ExceptionString(ex.ToString());
string str = ex.Message;
return false;
}
}
}
public static class GetDBConnection
{
public static DbConnection CreateDbConnection(string ConStr)
{
DbConnection dbConnection = null;
string text = ConStr;
string providerInvariantName = ConfigurationManager.AppSettings["ProviderName"];
if (text != null)
{
try
{
DbProviderFactory factory = DbProviderFactories.GetFactory(providerInvariantName);
dbConnection = factory.CreateConnection();
dbConnection.ConnectionString = text;
}
catch (Exception ex)
{
if (dbConnection != null)
{
dbConnection = null;
}
Console.WriteLine(ex.Message);
}
}
return dbConnection;
}
public static void AddParameterWithValue(this DbCommand command, string parameterName, object parameterValue, string Direction = "IN", string DType = "string")
{
string text = ConfigurationManager.AppSettings["ProviderName"];
string empty = string.Empty;
string text2 = text;
if (text2 != null)
{
if (text2 == "MySql.Data.MySqlClient")
{
parameterName = parameterName.Replace("@", "").Trim();
}
}
DbParameter dbParameter = command.CreateParameter();
if (Direction == "OUT")
{
dbParameter.Direction = ParameterDirection.Output;
}
else if (Direction == "OUT")
{
dbParameter.Direction = ParameterDirection.Input;
}
dbParameter.ParameterName = parameterName;
if (DType == "Images")
{
dbParameter.DbType = DbType.Binary;
}
dbParameter.Value = parameterValue;
command.Parameters.Add(dbParameter);
}
}
public class CustomDataAdapter : DbDataAdapter, IDataAdapter
{
MissingMappingAction IDataAdapter.MissingMappingAction
{
get
{
return base.MissingMappingAction;
}
set
{
base.MissingMappingAction = value;
}
}
MissingSchemaAction IDataAdapter.MissingSchemaAction
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
ITableMappingCollection IDataAdapter.TableMappings
{
get
{
return base.TableMappings;
}
}
int IDataAdapter.Fill(DataSet dataSet)
{
return this.Fill(dataSet);
}
DataTable[] IDataAdapter.FillSchema(DataSet dataSet, SchemaType schemaType)
{
return this.FillSchema(dataSet, schemaType);
}
IDataParameter[] IDataAdapter.GetFillParameters()
{
return this.GetFillParameters();
}
int IDataAdapter.Update(DataSet dataSet)
{
return this.Update(dataSet);
}
public int FillFromReader(DataTable dataTable, IDataReader dataReader)
{
return this.Fill(dataTable, dataReader);
}
}
}