uPLibrary.Networking.M2Mqtt.MqttClient throwing CommunicationException and OutOfMemoryException - out-of-memory

I am using uPLibrary.Networking.M2Mqtt to connect to MQTT broker.
var telemetryClient = new uPLibrary.Networking.M2Mqtt.MqttClient(
mqttBaseAddress, MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true,
new X509Certificate2($"certs/{rootCert}"), new X509Certificate2($"certs/{cert}", $"{certPw}"),
MqttSslProtocols.TLSv1_2
);
if (!telemetryClient.IsConnected)
{
try
{ // Following line is getting exceptions
telemetryClient.Connect(clientId, null, null, true, 10);
telemetryClient.ConnectionClosed += (sender, args) =>
{
IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Disconnected);
};
telemetryClient.Subscribe(new[] { topic }, new[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Connected);
}
catch (Exception exception)
{
CloseTelemetryStream(telemetryClient, true, topic);
Task.Delay(DelayBeforeReconnect).ContinueWith(t => ConnectAndSubscribeForTelemetryTopic(serialNumber, src, clientId, telemetryClient, telemetryStreamType, topic));
}
}
This has been working for a long time, without any serious issues.
After a while (months), I started getting two exceptions constantly, one after the other a lot of times from this line:
telemetryClient.Connect(clientId, null, null, true, 10);
The exceptions are:
uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException:
Exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException' was thrown. at
uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive(Byte[] msgBytes, Int32 timeout) at
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod)
and
System.OutOfMemoryException:
Exception of type 'System.OutOfMemoryException' was thrown. at
System.Threading.Thread.StartInternal() at
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod) at
DevicePortal.Telemetry.Service.Services.IotCoreServiceBase.ConnectAndSubscribeForTelemetryTopic(String serialNumber, String src, String clientId, MqttClient telemetryClient, String telemetryStreamType, String topic) in /src/DevicePortal.Telemetry.Service/Services/IotCoreServiceBase.cs:line 179

Related

SSRS Reports are not downloading [duplicate]

I would like to download a PDF report from our Microsoft Report Server using my C# code. I don't know why, but I' m doing something wrong. I always get an error back that the authentication failed (HTTP 401).
public static async Task<Stream> DownloadWebDocument(string url) {
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException(nameof(url));
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Credentials = new NetworkCredential("MyUsername", "MyPassword", "MyDomain");
//request.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("MyUsername:MyPassword"))}");
try {
using WebResponse response = await request.GetResponseAsync();
return response.GetResponseStream();
} catch (Exception ex) {
var a = ex.Message;
throw;
}
//return await DownloadWebDocument(uri);
}
This code always runs into the exception. But why?
PS:
As requested, here's the stack trace. There is no inner exception.
bei System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
bei System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
bei DE.ZA.TrailerLoadingAssistant.Web.Code.WebHelper.<DownloadWebDocument>d__0.MoveNext() in C:\Users\Reichelt\source\repos\DE.ZA.TrailerLoading\DE.ZA.TrailerLoadingAssistant.Web\Code\WebHelper.cs:Zeile 28.
I realized, that if I use request.Credentials = CredentialCache.DefaultCredentials, it works. So there must be something wrong with my credentials. But it's definitely no typo.
I've had this problem and it seemed someone was changing the network permissions. One week using Credentials would work then the next week using DefaultCredentials worked. Really strange, so I put in a Try/Catch and resort to the DefaultCredentials if the Service Account fails, see the code comment:
public class SRSHelper
{
private ReportingService2005 rsServ;
private ReportingExecution2005 rsExec = new ReportingExecution2005();
private ReportParameter[] reportParameters;
private ExecutionInfo execInfo = null;
public SRSHelper(string reportUserName, string decryptedPassword, string reportDomain, string reportServerURL)
{
rsServ = new ReportingService2005(reportServerURL);
rsExec.Url = reportServerURL + #"ReportExecution2005.asmx";
System.Net.NetworkCredential creds = new System.Net.NetworkCredential();
creds.UserName = reportUserName;
creds.Password = decryptedPassword;
creds.Domain = reportDomain;
rsExec.Credentials = creds;
rsServ.Credentials = creds;
}
public ReportParameter[] GetSRSReportParameters(string reportName)
{
string report = "/Reporting/" + reportName;
bool forRendering = false;
string historyID = null;
ParameterValue[] values = null;
DataSourceCredentials[] credentials = null;
try
{
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
catch
{
//If the Service Account credentials fail to work - try the users credentials - XYZ vendor regularly change things around or the network fails or for some reason beyond our control we have to change the settings.
rsExec.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
rsServ.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
}
Actually I use different method to render my report as PDF document:
public static byte[] DownloadAsPDF(string ReportServer, string ReportPath)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.ServerReport.ReportServerCredentials = new
CustomReportCredentials("MyUsername", "MyPassword", "MyDomain");
ReportViewer1.ProcessingMode =
Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri(ReportServer);
ReportViewer1.ServerReport.ReportPath = ReportPath;
byte[] bytes = ReportViewer1.ServerReport.Render("PDF");
return bytes;
}
public class CustomReportCredentials :
Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord,
string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord,
_DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string
user, out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}

Some emails delayed or not delivered when using system.web.mail in asp.net

//i have left out some parameters for readability
public static string MailForCandidate(string username, string FromAddr, string ToAddr, string strSubject)
{
try
{
MailMessage msg = new MailMessage();
string strMailBody = "Test body";
msg.To = ToAddr;
msg.From = FromAddr;
msg.BodyFormat = MailFormat.Html;
msg.Priority = MailPriority.High;
msg.Subject = strSubject;
msg.Body = strMailBody.ToString();
SmtpMail.SmtpServer = ConfigurationManager.AppSettings["mailServer"].ToString();
try
{
SmtpMail.Send(msg);
msg = null;
return "";
}
catch (Exception ex)
{
Util.Common.LogErrorMessage(ex);
msg = null;
return username;
}
}
catch (Exception ex)
{
throw ex;
}
}
I have the above function that i'm using to send emails from an IIS hosted .NET 3.5 asp.net application.
The emails are sent at the click of a button and the recipients are being read from a database table.
The problem i'm having is that some recipients get their emails with out any issue, others take far too long to receive their emails (sometimes after 24 hours) at which time the event they are supposed to participate in has expired (and this has legal implications to my company). And then finally, others do not receive the email completely.
The above MailForCandidate function is being called from SendCandidateMail below.
private void SendCandidateMail(int intEmailType)
{
try
{
ArrayList arrPending = new ArrayList();
ArrayList arrUnsent = new ArrayList();
string strCandidatename = string.Empty;
string stractualname = string.Empty;
int intUnsentCandCount = 0;
if (hdnUnsentNames.Value.Trim() != string.Empty)
{
arrUnsent.AddRange(hdnUnsentNames.Value.Split(','));
}
if (hdnPendingNames.Value.Trim() != string.Empty)
{
arrPending.AddRange(hdnPendingNames.Value.Split(','));
}
hdnUnsentNames.Value = string.Empty;
hdnPendingNames.Value = string.Empty;
if (!string.IsNullOrEmpty(hdnUnsent.Value) && !string.Empty.Equals(hdnUnsent.Value))
{
string[] strUnsIds = hdnUnsent.Value.Split('~');
for (int i = 0; i < strUnsIds.Length; i++)
{
DataSet dtsetCandidate = CandidatesListBL.GetCandidateDetails(Convert.ToInt32(strUnsIds[i]));
stractualname = arrUnsent[i].ToString();
if (dtsetCandidate.Tables[0].Rows.Count > 0)
{
if (dtsetCandidate.Tables[0].Rows[0]["Time"].ToString() != "0")
{
//i have left out some parameters for readability
strCandidatename = SendMail.MailForCandidate(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
}
else
strCandidatename = SendMail.MailForCandidateNoTime(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
if (strCandidatename.Trim().Equals(string.Empty))
{
hdnUnsentNames.Value = hdnUnsentNames.Value + stractualname + ",";
intUnsentCandCount = intUnsentCandCount + 1;
if (Convert.ToInt32(EnumMaster.EmailType.Customized) != intEmailType)
{
CandidatesListBL.UpdateCandidateStatus(Convert.ToInt32(strUnsIds[i]), "Sent");
CandidatesListBL.UpdateDateSent(Convert.ToInt32(strUnsIds[i]));
}
}
}
}
hdnUnsent.Value = string.Empty;
}
}
catch (Exception ex)
{
WESMessage.DisplayMessage(this, this.UpdatePanel1, DanielHac.TamperProofString.QueryStringEncode("MailFailed"), this.strinfo);
Common.LogErrorMessage(ex);
}
}
Below is what is being logged in the error log text file.
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Code
Exception Target Site: System.String MailForCandidate(System.String, System.String, System.String, System.Collections.ArrayList, System.String, System.String, System.String, System.String, System.String, System.String, UserSession, System.String, System.String, Int32, Int32)
Exception Stack Trace: at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
And
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Web_kxc2lbj5
Exception Target Site: Void SendCandidateMail(Int32)
Exception Stack Trace: at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Also
01/22/2017 3:23:04 PM ==> Exception Message: Request timed out.
101/22/2017 3:23:04 PM ==> Exception Source: Exception Target Site:
Exception Stack Trace: Exception To String: System.Web.HttpException:
Request timed out.
Then
101/22/2017 3:31:35 PM ==> Exception Message: Exception of type
'System.Exception' was thrown. 01/22/2017 3:31:35 PM ==> Exception
Source: App_Web_kxc2lbj5 Exception Target Site: Void
SendCandidateMail(Int32) Exception Stack Trace: at
Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType) Exception
To String: System.Exception: Exception of type 'System.Exception' was
thrown. at Pages_ExerciseDetails.SendCandidateMail(Int32
intEmailType)
I'm find it hard to troubleshot because it is occurring in production ONLY. In QA and Dev, emails are just going fine using the same SMTP server.
I will just post my comment here as the answer.
I resolved this bu just discarding the obsolete system.web.mail. I
re-wrote the code using System.Net.Mail & all issues are resolved,
performs even much faster.

Getting Unspecified error while adding CustomDocumentProperties in ms word using c#

I want to add CustomDocumentProperties into my existing MS Word docx file using c#.
I am able to open the file but when I am going to add CustomDocumentProperties it is giving me
below exception.
{"Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL))"}
One more thing when I tried this by initialize a new doc object, it is not giving me any error.
Below code I have used. Please help if I did any mistake here.
object type = Type.Missing;
Word.Application word;
Word._Document doc;
Word._Document doc1;
string filePath = "D:\\abc1.docx";
string targetFileName = "D:\\abc1.docx";
protected void Page_Load(object sender, EventArgs e)
{
word = new Word.Application();
word.Visible = false;
doc1 = word.Documents.Open(filePath, false);
SetDocumentProperty1("Subject", "Whitepaper");
GetDocumentProperty1("Subject", MsoDocProperties.msoPropertyTypeString);
doc1.SaveAs(targetFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
doc1.Close(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc1);
}
public void SetDocumentProperty1(string propertyName, string propertyValue)
{
object oDocCustomProps = doc1.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
object[] oArgs = {propertyName,false,
MsoDocProperties.msoPropertyTypeString,
propertyValue};
typeDocCustomProps.InvokeMember("Add", BindingFlags.Default |
BindingFlags.InvokeMethod, null,
oDocCustomProps, oArgs);
}
private object GetDocumentProperty1(string propertyName, MsoDocProperties type)
{
object returnVal = null;
object oDocCustomProps = doc1.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
object returned = typeDocCustomProps.InvokeMember("Item",
BindingFlags.Default |
BindingFlags.GetProperty, null,
oDocCustomProps, new object[] { propertyName });
Type typeDocAuthorProp = returned.GetType();
returnVal = typeDocAuthorProp.InvokeMember("Value",
BindingFlags.Default |
BindingFlags.GetProperty,
null, returned,
new object[] { }).ToString();
return returnVal;
}

WCF un-expected end of file error

Recently I have upgraded my project from .NET Framework 3.5 to 4.0. For WCF I am using custom basic authentication.
Before conversion, all was working fine. However, after conversion I am getting "Unexpected end of file error". The stack strace is as below :
at System.Xml.EncodingStreamWrapper.ProcessBuffer(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReplyCore(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpRequestContext.OnReply(Message message, TimeSpan timeout)
at System.ServiceModel.Activation.HostedHttpContext.OnReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestContextBase.Reply(Message message)
at ihv1Role.auth.BasicAuthenticationInterceptor.ProcessRequest(RequestContext& requestContext) in d:\src\auth\BasicAuthenticationInterceptor.cs:line 78
The class and method in which I am getting error are as below :
p
ublic class BasicAuthenticationInterceptor : RequestInterceptor
{
MembershipProvider provider;
string realm;
public BasicAuthenticationInterceptor(MembershipProvider provider, string realm)
: base(false)
{
this.provider = provider;
this.realm = realm;
}
protected string Realm
{
get { return realm; }
}
protected MembershipProvider Provider
{
get { return provider; }
}
public override void ProcessRequest(ref RequestContext requestContext)
{
HttpRequestMessageProperty request = (HttpRequestMessageProperty)requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
string[] credentials = ExtractCredentials(requestContext.RequestMessage);
if (credentials.Length > 0 && AuthenticateUser(credentials[0], credentials[1], IsTestMode))
{
InitializeSecurityContext(requestContext.RequestMessage, credentials[0]);
}
else
{
Message reply = Message.CreateMessage(MessageVersion.None, null);
HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };
responseProperty.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", Realm));
reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
requestContext.Reply(reply); // **Here I am getting error**
requestContext = null;
}
}
}
If the username and password in header are valid then whole service runs well. I am getting this error only if request is not authenticated.
Any solution?
Thanks
Resolved it my self :
I had added tag twice in Web.config.
Removed it and now my service is working fine.

Unable to create user on windows server 2008 due to access permission

I am getting below error while trying to create user on remote computer.
System.UnauthorizedAccessException: General access denied error at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.GetInfo() at System.DirectoryServices.DirectoryEntry.RefreshCache() at System.DirectoryServices.AccountManagement.PrincipalContext.DoMachineInit() at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() at System.DirectoryServices.AccountManagement.PrincipalContext.ContextForType(Type t) at System.DirectoryServices.AccountManagement.Principal.GetStoreCtxToUse() at System.DirectoryServices.AccountManagement.Principal.set_DisplayName(String value) at testemail.CreateLocalWindowsAccount(String username, String password, String displayName, String description, Boolean canChangePwd, Boolean pwdExpires)
here is the code.
public void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Machine, "127.0.0.1");
UserPrincipal user = new UserPrincipal(context);
user.SetPassword(password);
user.DisplayName = displayName;
user.Name = username;
user.Description = description;
user.UserCannotChangePassword = canChangePwd;
user.PasswordNeverExpires = pwdExpires;
user.Save();
//now add user to "Users" group so it displays in Control Panel
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users");
group.Members.Add(user);
group.Save();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Resources