Problems reading from Microsoft Messaging Queues in C# - c#-4.0

I have problems reading from my MSMQ. When I write to the queue, it works perfectly, but when I try to read that message from the queue, I get the following exception: "The queue does not exist or you do not have sufficient permissions to perform the operation." The queue does exists, and I have full permissions on the machine and queue. Here is my code:
public string path = #".\private$\";
public void WriteToQueue(string QueueName, object messageObject)
{
try
{
path = path + QueueName;
MessageQueue msmq = null;
if (!MessageQueue.Exists(path))
{
msmq = MessageQueue.Create(path);
}
else
{
msmq = new MessageQueue(path);
}
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msmq.Send(messageObject);
msmq.Close();
}
catch (MessageQueueException ex)
{
System.ArgumentException argEx = neArgumentException(ex.ToString());
throw argEx;
}
path = #".\private$\";
}
public string ReadQueue(string QueueName)
{
try
{
path = path + QueueName;
MessageQueue msmq = new MessageQueue(path);
string msg;
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msg = msmq.Receive().Body.ToString(); //exception is thrown here
path = #".\private$\";
return msg;
}
catch (Exception ex)
{
return null;
}
}
can the problem maybe be with reading it as type of string? Maybe not in the right format?

Try this:
public string path = ".\\private$\\";
'#' doesn't work for me too.

Related

cannot access the file because it is using by another program Error

I have been fighting with this issue since last week.still not able to solve.
i am sending file to client machine once i get in server automatically.but so many time when i handle file it throw an error that Cannot access the file because it is using by another program.
below my code
private static string SaveFileStream(string filePath, Stream stream, string Filename1)
{
string localresponse;
try
{
//this.SaveFileStream(System.Configuration.ConfigurationSettings.AppSettings[fileToPush.FileType].ToString() + "\\" + fileToPush.FileName, new MemoryStream(fileToPush.Content));
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Dispose();
}
FileInfo info = new FileInfo(filePath);
ExtractFile(info);
localresponse = "Successful";
}
catch (Exception ex)
{
localresponse = ex.Message;
}
return localresponse;
}

CmisInvalidArgumentException bad request exception

i am getting below error while run this program
i am using SharePoint server 2010 and recently i am install danish language pack in SharePoint server for client environment . but after this when ever i am run below code
i am getting below exceptions
org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException: Bad Request
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:453)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:601)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.NavigationServiceImpl.getChildren(NavigationServiceImpl.java:86)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl$2.fetchPage(FolderImpl.java:285)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getCurrentPage(AbstractIterator.java:132)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getTotalNumItems(AbstractIterator.java:70)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterable.getTotalNumItems(AbstractIterable.java:94)
at ShareTest1.main(ShareTest1.java:188)
public class ShareTest
{
static Session session = null;
static Map<String,Map<String, String>> allPropMap=new HashMap<String,Map<String, String>>();
static void getSubTypes(Tree tree)
{
ObjectType objType = (ObjectType) tree.getItem();
if(objType instanceof DocumentType)
{
System.out.println("\n\nType name "+objType.getDisplayName());
System.out.println("Type Id "+objType.getId());
ObjectType typeDoc=session.getTypeDefinition(objType.getId());
Map<String,PropertyDefinition<?>> mp=typeDoc.getPropertyDefinitions();
for(String key:mp.keySet())
{
PropertyDefinition<?> propdef=mp.get(key);
HashMap<String,String> propMap=new HashMap<String,String>();
propMap.put("id",propdef.getId());
propMap.put("displayName",propdef.getDisplayName());
System.out.println("\nId="+propMap.get("id")+" DisplayName="+propMap.get("displayName"));
System.out.println("Property Type = "+propdef.getPropertyType().toString());
System.out.println("Property Name = "+propdef.getPropertyType().name());
System.out.println("Property Local Namespace = "+propdef.getLocalNamespace());
if(propdef.getChoices()!=null)
{
System.out.println("Choices size "+propdef.getChoices().size());
}
if(propdef.getExtensions()!=null)
{
System.out.println("Extensions "+propdef.getExtensions().size());
}
allPropMap.put(propdef.getId(),propMap);
}
List lstc=tree.getChildren();
System.out.println("\nSize of list "+lstc.size());
for (int i = 0; i < lstc.size(); i++) {
getSubTypes((Tree) lstc.get(i));
}
}
}
public static void main(String[] args)
{
/**
* Get a CMIS session.
*/
String user="parag.patel";
String pwd="Admin123";
/*Repository : Abc*/
String url="http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo";
String repositoryId="6B4D3830-65E5-49C9-9A02-5D67DB1FE87B";
// Default factory implementation of client runtime.
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// user credentials
parameter.put(SessionParameter.USER, "parag.patel");
parameter.put(SessionParameter.PASSWORD, "Admin123");
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, "http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo");
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.REPOSITORY_ID, "6B4D3830-65E5-49C9-9A02-5D67DB1FE87B");
parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "DK");
parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "da");
parameter.put(SessionParameter.LOCALE_VARIANT, "");
parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, CmisBindingFactory.STANDARD_AUTHENTICATION_PROVIDER);
// create session
Session session = factory.createSession(parameter);
if(repositoryId!=null)
{
parameter.put(SessionParameter.REPOSITORY_ID, repositoryId);
session=factory.createSession(parameter);
RepositoryInfo repInfo=session.getRepositoryInfo();
System.out.println("Repository Id "+repInfo.getId());
System.out.println("Repository Name "+repInfo.getName());
System.out.println("Repository cmis version supported "+repInfo.getCmisVersionSupported());
System.out.println("Sharepoint product "+repInfo.getProductName());
System.out.println("Sharepoint version "+repInfo.getProductVersion());
System.out.println("Root folder id "+repInfo.getRootFolderId());
try
{
AclCapabilities cap=session.getRepositoryInfo().getAclCapabilities();
OperationContext operationContext = session.createOperationContext();
int maxItemsPerPage=5;
//operationContext.setMaxItemsPerPage(maxItemsPerPage);
int documentCount=0;
session.setDefaultContext(operationContext);
CmisObject object = session.getObject(new ObjectIdImpl(repInfo.getRootFolderId()));
Folder folder = (Folder) object;
System.out.println("======================= Root folder "+folder.getName());
ItemIterable<CmisObject> children = folder.getChildren();
long to=folder.getChildren().getTotalNumItems();
System.out.println("Total Children "+to);
Iterator<CmisObject> iterator = children.iterator();
while (iterator.hasNext()) {
CmisObject child = iterator.next();
System.out.println("\n\nChild Id "+child.getId());
System.out.println("Child Name "+child.getName());
if (child.getBaseTypeId().value().equals(ObjectType.FOLDER_BASETYPE_ID))
{
System.out.println("Type : Folder");
Folder ftemp=(Folder) child;
long tot=ftemp.getChildren().getTotalNumItems();
System.out.println("Total Children "+tot);
ItemIterable<CmisObject> ftempchildren = ftemp.getChildren();
Iterator<CmisObject> ftempIt = ftempchildren.iterator();
int folderDoc=0;
while (ftempIt.hasNext()) {
CmisObject subchild = ftempIt.next();
if(subchild.getBaseTypeId().value().equals(ObjectType.DOCUMENT_BASETYPE_ID))
{
System.out.println("============ SubDoc "+subchild.getName());
folderDoc++;
documentCount++;
}
}
System.out.println("Folder "+child.getName()+" No of documents="+(folderDoc));
}
else
{
System.out.println("Type : Document "+child.getName());
documentCount++;
}
}
System.out.println("\n\nTotal no of documents "+documentCount);
}
catch(CmisPermissionDeniedException pd)
{
System.out.println("Error ********** Permission Denied ***************** ");
pd.printStackTrace();
}
catch (CmisObjectNotFoundException co) {
System.out.println("Error ******** Root folder not found ***************");
co.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
else
{
System.out.println("Else");
Repository soleRepository=factory.getRepositories(
parameter).get(0);
session = soleRepository.createSession();
}
}
}
here it is my lib which i used in above code .
chemistry-opencmis-client-api-0.9.0
chemistry-opencmis-client-bindings-0.9.0
chemistry-opencmis-client-impl-0.9.0
chemistry-opencmis-commons-api-0.9.0
chemistry-opencmis-commons-impl-0.9.0
log4j-1.2.14
slf4j-api-1.6.1
slf4j-log4j12-1.6.1
it works fine when i am trying to connect repository (url) which is created in english language .
but when try to connect with the danish .repository then getting error.
The best thing you can do is to increase the SharePoint log level for CMIS. Sometimes the logs provide a clue.
The SharePoint 2010 CMIS implementaion isn't a 100% spec compliant. OpenCMIS 0.12.0 contains a few workarounds for SharePoint 2010 and 2013. Most of them a little things like an extra requied URL parameter that isn't in the spec. I wouldn't be supprised if this is something similar.

call log function in windows phone 8

I am developing VoIP application (Dialler) in windows phone 8, In that application contain dial pad , contacts, call log , I already create a dial pad and contact list, I need to develop a call log function in that application. I struggle in to create a call log for windows phone 8 any help please
This is a class that creates an XML file which holds the logs of all calls. You didn't specify the question enough or what you want to do, or what have you already tried. So here is an idea of what you should implement:
public class Logger
{
private static string logPath;
public Logger()
{
logPath = "/Logs/log.xml";
}
public void LogData(string contactName, string duration)
{
Object thisLock = new Object();
logPath += DateTime.Now.ToShortDateString().Replace('.', '_') + ".log";
XmlDocument doc = new XmlDocument();
lock (thisLock)
{
try
{
XmlNode root = null;
if (File.Exists(logPath))
{
doc.Load(logPath);
root = doc.SelectSingleNode("/Call");
}
else
{
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
root = doc.AppendChild(doc.CreateElement("Call"));
}
XmlElement call = doc.CreateElement("call");
root.AppendChild(call);
XmlElement xcontactName = doc.CreateElement("contactName");
xcontactName.InnerText = contactName;
call.AppendChild(xcontactName);
XmlElement xdate = doc.CreateElement("date");
xdate.InnerText = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
call.AppendChild(xdate);
XmlElement xduration = doc.CreateElement("duration");
xduration.InnerText = duration;
call.AppendChild(xduration);
doc.Save(logPath);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
}

Plugin code to update another entity when case is created mscrm 2011

Im new with plugin. my problem is, When the case is created, i need to update the case id into ledger. What connect this two is the leadid. in my case i rename lead as outbound call.
this is my code. I dont know whether it is correct or not. Hope you guys can help me with this because it gives me error. I manage to register it. no problem to build and register but when the case is created, it gives me error.
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.Web.Services;
/*
* Purpose: 1) To update case number into lejar
*
* Triggered upon CREATE message by record in Case form.
*/
namespace UpdateLejar
{
public class UpdateLejar : IPlugin
{
/*public void printLogFile(String exMessage, String eventMessage, String pluginFile)
{
DateTime date = DateTime.Today;
String fileName = date.ToString("yyyyMdd");
String timestamp = DateTime.Now.ToString();
string path = #"C:\CRM Integration\PLUGIN\UpdateLejar\Log\" + fileName;
//open if file exist, check file..
if (File.Exists(path))
{
//if exist, append
using (StreamWriter sw = File.AppendText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
else
{
//if no exist, create new file
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
}*/
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//for update and create event
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity targetEntity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents a connection.
if (targetEntity.LogicalName != "incident")
{
return;
}
else
{
try
{
//triggered upon create message
if (context.MessageName == "Create")
{
Guid recordid = new Guid(context.OutputParameters["incidentid"].ToString());
EntityReference app_inc_id = new EntityReference();
app_inc_id = targetEntity.GetAttributeValue<EntityReference>("new_outboundcalllid");
Entity member = service.Retrieve("new_lejer", ((EntityReference)targetEntity["new_outboundcallid"]).Id, new ColumnSet(true));
//DateTime createdon = targetEntity.GetAttributeValue<DateTime>("createdon");
if (app_inc_id != null)
{
if (targetEntity.Attributes.Contains("new_outboundcallid") == member.Attributes.Contains("new_outboundcalllistid_lejer"))
{
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
service.Update(member);
}
}
}
tracingService.Trace("Lejar updated.");
}
catch (FaultException<OrganizationServiceFault> ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
throw new InvalidPluginExecutionException("An error occurred in UpdateLejar plug-in.", ex);
}
catch (Exception ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
tracingService.Trace("UpdateLejar: {0}", ex.ToString());
throw;
}
}
}
}
}
}
Please check,
is that entity containing the attributes or not.
check it and try:
if (targetEntity.Contains("new_outboundcallid"))
((EntityReference)targetEntity["new_outboundcallid"]).Id
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
What is new_ringkasanlejarid's type? You're setting a string to it. If new_ringkasanlejarid is an entity reference, this might be causing problems.
You might want to share the error details or trace log, all we can do is assume what the problem is at the moment.

Is it possible to use IMAP Query Terms in Javamail with GMail?

I am trying to programmatically retrieve the Call Log messages that are backup up from my android phone by a little application called SMSBackup (highly recommended).
What I want to do is to be able to retrieve the call logs for a particular day. I have tried the following program, using JavaMail:
public List<CallLogEntry> getCallLog(String username, String password, Date date, TimeZone tz) {
Store store = null;
try {
store = MailUtils.getGmailImapStore(username, password);
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new Exception("No default folder");
Folder inboxfolder = folder.getFolder("Call log");
if (inboxfolder == null)
throw new Exception("No INBOX");
inboxfolder.open(Folder.READ_ONLY);
Date fromMidnight = new Date(TimeUtils.fromMidnight(date.getTime(), tz));
Date toMidnight = new Date(TimeUtils.toMidnight(date.getTime(), 0, tz));
SentDateTerm fromTerm = new SentDateTerm(SentDateTerm.GT, fromMidnight);
SentDateTerm toTerm = new SentDateTerm(SentDateTerm.LT, toMidnight);
AndTerm searchTerms = new AndTerm(fromTerm, toTerm);
Message[] msgs = inboxfolder.search(searchTerms);
FetchProfile fp = new FetchProfile();
fp.add("Subject");
fp.add("Content");
fp.add("From");
fp.add("SentDate");
inboxfolder.fetch(msgs, fp);
List<CallLogEntry> callLog = new ArrayList<CallLogEntry>();
for (Message message : msgs) {
CallLogEntry entry = new CallLogEntry();
entry.subject = message.getSubject();
entry.body = (String) message.getContent();
callLog.add(entry);
}
inboxfolder.close(false);
store.close();
return callLog;
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
} catch (MessagingException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (store != null)
store.close();
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
return null;
}
My two utility methods (fromMidnight / toMidnight):
public static final long fromMidnight(long time, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 1);
return c.getTimeInMillis();
}
public static final long toMidnight(long time, int nDays, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time + nDays*MILLIS_IN_DAY);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTimeInMillis();
}
However, for some reason:
while eventually executing, it takes about 3 minutes to complete
I'm getting back the entire Call log, i.e. the entire content of the "Call Log" folder in my mailbox
What am I missing?
The main thing that you're missing is that the underlying IMAP SEARCH syntax supports only dates, not date-times. So your query will result in JavaMail issuing the command:
A001 SEARCH SENTBEFORE 16-JAN-2011 SENTSINCE 16-JAN-2011 ALL
(Put a breakpoint in IMAPProtocol.issueSearch() to see this.)
GMail appears to freak out on this query, which logically cannot match any messages. Try switching your logic to a single term using SentDateTerm.EQ (which maps to SENTON) and it should work:
SentDateTerm term = new SentDateTerm(SentDateTerm.EQ, date.getTime());
Message[] msgs = inboxfolder.search(term);

Resources