In .Net framework 4.5 async and await keywords are introduced to do async calls.
I have used them in web applications too. I came to know that it can also be done using doing delegates.
Below are my sample snippet showing how async calls are done
Public void binddata()
{
certificate = HelperMethods.GetStoreCertifcate(Thumbprint);
ListHostedServices(SubscriptionId, certificate, Version);
hostedservicesview.ActiveViewIndex = 0;
ListStorageAccounts(SubscriptionId, certificate, Version);
}
public async void ListHostedServices(string subscriptionId, X509Certificate2 certificate, string version)
{
string hittingUri = String.Format("https://management.core.windows.net/{0}/" + "services/hostedservices",SubscriptionId);
XmlDocument responsebody= await HelperMethods.GetXmlDocument(hittingUri, certificate, version);
if (responsebody != null)
{
var result = responsebody.GetElementsByTagName("HostedServiceProperties");
hostedservices = new DataTable();
hostedservices.Columns.Add("Url");
hostedservices.Columns.Add("ServiceName");
hostedservices.Columns.Add("Location");
hostedservices.Columns.Add("Label");
hostedservices.Columns.Add("Status");
hostedservices.Columns.Add("DateCreated");
hostedservices.Columns.Add("DateLastModified");
foreach (XmlNode hsnode in result)
{
DataRow hsrow = hostedservices.NewRow();
hsrow["Url"] = hsnode.ParentNode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Url").Any() ?
hsnode.ParentNode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Url").First().InnerText : string.Empty;
hsrow["ServiceName"] = hsnode.ParentNode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "ServiceName").Any() ?
hsnode.ParentNode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "ServiceName").First().InnerText : string.Empty;
hsrow["Location"] = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Location").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Location").First().InnerText : string.Empty;
// IF location is empty, it means affinity group is returned, Pull location from affinity group
if (String.IsNullOrEmpty(hsrow["Location"].ToString()))
{
string affnitygroup = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "AffinityGroup").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "AffinityGroup").First().InnerText : string.Empty;
certificate = HelperMethods.GetStoreCertifcate(Thumbprint);
hsrow["Location"] = await HelperMethods.GetAffinityGroupLocation(subscriptionId, certificate, Version, affnitygroup);
}
hsrow["Label"] = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Label").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Label").First().InnerText : string.Empty;
hsrow["Status"] = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Status").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "Status").First().InnerText : string.Empty;
hsrow["DateCreated"] = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "DateCreated").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "DateCreated").First().InnerText : string.Empty;
hsrow["DateLastModified"] = hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "DateLastModified").Any() ?
hsnode.ChildNodes.OfType<XmlElement>().Where(x => x.Name == "DateLastModified").First().InnerText : string.Empty;
hostedservices.Rows.Add(hsrow);
}
lbl_count.Text = hostedservices.Rows.Count.ToString();
HostedServicesList.DataSource = hostedservices;
HostedServicesList.DataBind();
}
else
{
}
}
**XmlDocument responsebody= await HelperMethods.GetXmlDocument(hittingUri, certificate, version);**
The method definition is as follows
public static async Task<XmlDocument> GetXmlDocument(string hittingUrl, X509Certificate2 certificate, string Version)
{
HttpWebRequest request;
XmlDocument responsebody = new XmlDocument();
// string hittingUri = "https://management.core.windows.net/{0}/" + "services/hostedservices";
Uri uri = new Uri(hittingUrl);
request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("x-ms-version", Version);
request.ClientCertificates.Add(certificate);
request.ContentType = "application/xml";
HttpWebResponse webresponse= null;
try
{
webresponse = (HttpWebResponse)await request.GetResponseAsync();
}
catch (Exception)
{
}
HttpStatusCode statuscode = webresponse.StatusCode;
if (webresponse.ContentLength > 0)
{
using (XmlReader reader =XmlReader.Create(webresponse.GetResponseStream()))
{
responsebody.Load(reader);
}
}
if (statuscode.Equals(HttpStatusCode.OK))
{
return responsebody;
}
else
{
return null;
}
}
Similarly above 2 methods also have same kind of listing.
Its taking me approximately 12-15 seconds to retrieve data of 11+19+6 records.
Could you guys help me in optimizing this code so that it will be much faster.
First you need to profile your code to see where exactly are you loosing your time. If the GetXMLDocument is taking up most of the time then it may be that the server is not as responsive
Outside of that my guess would be that your foreach loop is taking the most amount of time because you are essentially searching through all the elements in each statement in here.
Another way of doing this could be
Dictionary<string, string> nvpairsForColumns = new Dictionary { "Url", String.Empty }; // add all valid column headers here
foreach(var xelement in hsnode.ParentNode.ChildNodes.OfType<XmlElement>)
{
if(nvparisForColumns.ContainsKey(xelement.Name)
&& String.IsNullOrEmpty(nvpairsForColumns[xlement.Name])) // assumption String.Empty is not a valid entry else keep another Dictionary<string,bool> to tag when done with first
{
nvpairsForColumns[xelement.Name] = xelement.InnerText;
}
}
Related
I'm using .NET Core 3.1 but I encountered a weird problem!
the problem is any uploaded image the size of it is 0KB
when I restart the IIS and trying again will upload it without any problem but after that, the problem returns back.
I tried this solution by making my code async but with no luck
I changed my system file to be accessible by my Application pool user but with no luck
Here is my code :
public Document shareWithUsers([FromForm] CreateDocumentDto documentDto)
{
List<CreateUserType1DocumentsDto> listOfCreateUserType1Documents = new List<CreateUserType1DocumentsDto>();
List<CreateHDDocumentsDto> listOfCreateHDDocuments = new List<CreateHDDocumentsDto>();
if (documentDto.listOfUserType1Documents != null)
{
foreach (var item in documentDto.listOfUserType1Documents)
{
listOfCreateUserType1Documents.Add(JsonConvert.DeserializeObject<CreateUserType1DocumentsDto>(item));
}
}
else if (documentDto.listOfHDDocuments != null)
{
foreach (var item in documentDto.listOfHDDocuments)
{
listOfCreateHDDocuments.Add(JsonConvert.DeserializeObject<CreateHDDocumentsDto>(item));
}
}
if (documentDto.sharedText == null)
{
if (documentDto.document != null) //that mean user upload file
{
if (documentDto.document.Length > 0)
{
var UploadedFilesPath = Path.Combine(hosting.WebRootPath/*wwwroot path*/, "UploadedFiles" /*folder name in wwwroot path*/);
var filePath = Path.Combine(UploadedFilesPath, documentDto.document.FileName);
//documentDto.docUrl = filePath;
var documentObject = new Document();
using (var stream = new FileStream(filePath, FileMode.Create))
{
documentDto.document.CopyToAsync(stream);// Use stream
}
if (documentDto.listOfUserType1Documents != null)
{
documentObject.listOfUserType1Documents = ObjectMapper.Map<List<UserType1Documents>>(listOfCreateUserType1Documents);
}
else if (documentDto.listOfHDDocuments != null)
{
documentObject.listOfHDDocuments = ObjectMapper.Map<List<HDDocuments>>(listOfCreateHDDocuments);
}
documentObject.docTtitle = documentDto.docTtitle;
documentObject.docName = documentDto.docName;
documentObject.docUrl = filePath;
return _repository.Insert(documentObject);
}
}
}
else
{ //that mean user upload text
var documentObject = new Document();
if (documentDto.listOfUserType1Documents != null)
{
documentObject.listOfUserType1Documents = ObjectMapper.Map<List<UserType1Documents>>(listOfCreateUserType1Documents);
}
else if (documentDto.listOfHDDocuments != null)
{
documentObject.listOfHDDocuments = ObjectMapper.Map<List<HDDocuments>>(listOfCreateHDDocuments);
}
documentObject.sharedText = documentDto.sharedText;
return _repository.Insert(documentObject);
}
return null;
}
My code works only if I change both of them (CopyTo and Insert ) to Async with await
await CopyToAsync()
await InsertAsync()
I have the following issue using ASP.NET Core 2.2 and Automapper 9.0.0:
I have a Entity that I map to a dto, this works fine. Inside that entity are a few entities as well. These cannot be flattened as they are also needed by our client. There is however one property within those nested entities that need additional mapping.
within the Profile class of the overlapping Entity i do this:
public class OperationalToPalletResultProfile : Profile
{
public OperationalToPalletResultProfile()
{
string lang = null;
CreateMap<TblDatOperationalHUTrace, PalletResult>()
.ForMember(dest => dest.TransCode, act => act.MapFrom((src, _, transactionCode, ctx) =>
ctx.Mapper.Map<TblLstCode, TransactionCodeResult>(src.TransCode)));
}
}
This effectively maps the TblLstCode to TransactionCodeResult correctly. However the "DisplayDesc" property of the TransactionCodeResult remains null...
Note: the "lang" property gets set with the "ProjectTo" method:
var values = await query
.Take(5000)
.ProjectTo<PalletResult>(mapper.ConfigurationProvider, new { lang = language })
.ToListAsync()
.ConfigureAwait(false);
I have tried:
1- Using "AfterMap" in Profile class (result: DisplayDesc = null)
CreateMap<TblDatOperationalHUTrace, PalletResult>()
.ForMember(dest => dest.TransCode, act => act.MapFrom((src, _, transactionCode, ctx) =>
ctx.Mapper.Map<TblLstCode, TransactionCodeResult>(src.TransCode, opt =>
opt.AfterMap((source, destination) =>
destination.DisplayDesc = $"[{destination.ShortName}] {destination.DescToLanguageDesc(destination, lang)}"))))
Note: DescToLanguageDesc is a function that finds a property in the entity with reflection (this works and is not part of the problem)
2- Creating an IMappingAction to use in the Profile of the SubEntity (result: DisplayDesc = null)
public class TransactionCodeTranslation : IMappingAction<TblLstCode, TransactionCodeResult>
{
private readonly IHttpContextAccessor httpContextAccessor;
public TransactionCodeTranslation(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void Process(TblLstCode source, TransactionCodeResult destination, ResolutionContext context)
{
//Get language from httpContext - this works correctly
destination.DisplayDesc = $"[{source.ShortName}] {source.DescToLanguageDesc(source, language)}";
}
}
public class TransactionCodeProfile : Profile
{
public TransactionCodeProfile()
{
string language = string.Empty;
CreateMap<TblLstCode, TransactionCodeResult>()
.AfterMap<TransactionCodeTranslation>();
}
}
This doesn't work. HOWEVER if I use option 2 directly:
var tc = await codeRepo.TableNoTracking.FirstOrDefaultAsync(x => x.ShortName == "[something]").ConfigureAwait(false);
var transactionCode = mapper.Map<TblLstCode, TransactionCodeResult>(tc);
Then it works correctly! But that would mean i would have to loop my result and map every object in the result again...
Is there a way to do it like option 1?
Thank you!
Edit 1:
Per Lucian Bargaoanu's request i added a BuildExecutionPlan:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<TblDatOperationalHUTrace, PalletResult>()
.ForMember(dest => dest.TransCode, act => act.MapFrom((src, _, transactionCode, ctx) =>
ctx.Mapper.Map<TblLstCode, TransactionCodeResult>(src.TransCode, opt =>
opt.AfterMap((source, destination) =>
destination.DisplayDesc = $"[{destination.ShortName}] {destination.DescToLanguageDesc(destination, language)}"))));
cfg.CreateMap<TblLstCode, TransactionCodeResult>()
.AfterMap<TransactionCodeTranslation>();
});
var expression = config.BuildExecutionPlan(typeof(TblDatOperationalHUTrace), typeof(PalletResult));
var expression2 = config.BuildExecutionPlan(typeof(TblLstCode), typeof(TransactionCodeResult));
Result of expression:
(src, dest, ctxt) =>
{
PalletResult typeMapDestination;
return (src == null)
? null
: {
typeMapDestination = dest ?? new PalletResult();
try
{
var resolvedValue = mappingFunction.Invoke(
src,
typeMapDestination,
typeMapDestination.TransCode,
ctxt);
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.TransCode = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
return typeMapDestination;
};
}
Result Expression2:
(src, dest, ctxt) =>
{
TransactionCodeResult typeMapDestination;
return (src == null)
? null
: {
typeMapDestination = dest ?? new TransactionCodeResult();
try
{
var resolvedValue = ((src == null) || false) ? default(int) : src.Id;
typeMapDestination.Id = resolvedValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return default(int);
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.ShortName;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.ShortName = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
try
{
var resolvedValue = ((src == null) || false) ? default(int) : src.CodeTypeId;
typeMapDestination.CodeTypeId = resolvedValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return default(int);
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.DescLC;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.DescLC = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.DescEN;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.DescEN = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.DescFR;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.DescFR = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.DescGE;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.DescGE = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
try
{
var resolvedValue = ((src == null) || false) ? null : src.DescNL;
var propertyValue = (resolvedValue == null) ? null : resolvedValue;
typeMapDestination.DescNL = propertyValue;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(
"Error mapping types.",
ex,
AutoMapper.TypePair,
TypeMap,
PropertyMap);
return null;
}
afterFunction.Invoke(src, typeMapDestination, ctxt);
return typeMapDestination;
};
}
EDIT 2:
Ok, I actually found the solution. I was overcomplicating things for no reason...
I changed OperationalToPalletResultProfile to:
public class OperationalToPalletResultProfile : Profile
{
public OperationalToPalletResultProfile()
{
CreateMap<TblDatOperationalHUTrace, PalletResult>();
}
}
The TransactionCodeProfile remained the same:
public class TransactionCodeProfile : Profile
{
public TransactionCodeProfile()
{
CreateMap<TblLstCode, TransactionCodeResult>()
.AfterMap<TransactionCodeTranslation>();
}
}
And then where i use my mapping i changed this:
//results as TblDatOperationalHUTrace
var queryresult = await query
.Take(5000)
//.ProjectTo<PalletResult>(mapper.ConfigurationProvider) Don't do the mapping here anymore
.ToListAsync()
.ConfigureAwait(false);
//Map results to PalletResult
var values = mapper.Map<List<TblDatOperationalHUTrace>, List<PalletResult>>(queryresult); //Do the mapping here
Ok i actually found the solution myself:
I changed OperationalToPalletResultProfile to:
public class OperationalToPalletResultProfile : Profile
{
public OperationalToPalletResultProfile()
{
CreateMap<TblDatOperationalHUTrace, PalletResult>();
}
}
The TransactionCodeProfile remained the same:
public class TransactionCodeProfile : Profile
{
public TransactionCodeProfile()
{
CreateMap<TblLstCode, TransactionCodeResult>()
.AfterMap<TransactionCodeTranslation>();
}
}
And then where i use my mapping i changed this:
//results as TblDatOperationalHUTrace
var queryresult = await query
.Take(5000)
//.ProjectTo<PalletResult>(mapper.ConfigurationProvider) Don't do the mapping here anymore
.ToListAsync()
.ConfigureAwait(false);
//Map results to PalletResult
var values = mapper.Map<List<TblDatOperationalHUTrace>, List<PalletResult>>(queryresult); //Do the mapping here
And then it works like it's supposed to.
I found out how to determine the object type from URL for SharePoint on prem:
https://blogs.msdn.microsoft.com/sanjaynarang/2009/04/06/find-sharepoint-object-type-from-url/
But I didn't find anything for SharePoint Online (CSOM).
Is it possible for SharePoint online?
For the most scenarios such as:
folder url, e.g. https://contoso.sharepoint.com//Documents/Forms/AllItems.aspx?RootFolder=%2FDocuments%2FArchive
list item url, e.g. https://contoso.sharepoint.com/Lists/ShoppingCart/DispForm.aspx?ID=9
list/library url, e.g. https://contoso.sharepoint.com/Lists/Announcements
page url, e.g. https://contoso.sharepoint.com/Lists/Announcements/Newsletter.aspx
the following example demonstrates how to determine client object type:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using Microsoft.SharePoint.Client;
namespace O365Console
{
static class ClientObjectExtensions
{
public static ClientObject ResolveClientObjectFromUrl(string resourceUrl, ICredentials credentials)
{
ClientObject targetObject = null;
var resourceUri = new Uri(resourceUrl);
using (var rootCtx = new ClientContext(resourceUri.Scheme + Uri.SchemeDelimiter + resourceUri.Host))
{
rootCtx.Credentials = credentials;
var webUrl = Web.WebUrlFromPageUrlDirect(rootCtx, resourceUri);
using (var ctx = new ClientContext(webUrl.ToString()))
{
ctx.Credentials = credentials;
var queryBag = System.Web.HttpUtility.ParseQueryString(resourceUri.Query);
if (queryBag["Id"] != null)
{
var listUrl = string.Join(string.Empty,
resourceUri.Segments.Take(resourceUri.Segments.Length - 1));
var list = ctx.Web.GetList(listUrl);
targetObject = TryRetrieve(() => list.GetItemById(Convert.ToInt32(queryBag["Id"])));
}
else if (queryBag["RootFolder"] != null)
{
var folderUrl = HttpUtility.UrlDecode(queryBag["RootFolder"]);
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(folderUrl));
}
else if (queryBag.Count > 0)
{
throw new Exception("Unsupported query string parameter found");
}
else
{
targetObject = TryRetrieve(() => ctx.Web.GetFileByServerRelativeUrl(resourceUri.AbsolutePath));
if (targetObject == null)
{
targetObject = TryRetrieve(() => ctx.Web.GetList(resourceUri.AbsolutePath),list => list.RootFolder);
if (targetObject == null || ((List)targetObject).RootFolder.ServerRelativeUrl != resourceUri.AbsolutePath)
targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(resourceUri.AbsolutePath));
}
}
}
}
return targetObject;
}
private static T TryRetrieve<T>(Func<T> loadMethod, params Expression<Func<T,object>>[] retrievals) where T : ClientObject
{
try
{
var targetObject = loadMethod();
targetObject.Context.Load(targetObject, retrievals);
targetObject.Context.ExecuteQuery();
return targetObject;
}
catch
{
}
return default(T);
}
}
}
Usage
var credentials = GetCredentials(userName, password);
var clientObj = ClientObjectExtensions.ResolveClientObjectFromUrl("https://contoso.sharepoint.com/Lists/Announcements", credentials);
Console.WriteLine(clientObj.GetType().Name);
where
static ICredentials GetCredentials(string userName,string password)
{
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
return new SharePointOnlineCredentials(userName, securePassword);
}
I use sqldependency AND signalR AND thread but it goes on infinite loop
combine BackgroundWorker in global.aspx and sqldependency and signalR
I dont know about problem please help me.
void Application_Start(object sender, EventArgs e)
{
//var session = HttpContext.Current.Session;
//if (session != null && HttpContext.Current != null)
//{
try
{
CSASPNETBackgroundWorker.BackgroundWorker worker = new CSASPNETBackgroundWorker.BackgroundWorker();
worker.DoWork += new CSASPNETBackgroundWorker.BackgroundWorker.DoWorkEventHandler(worker_DoWork);
worker.RunWorker(null);
// This Background Worker is Applicatoin Level,
// so it will keep working and it is shared by all users.
Application["worker"] = worker;
// Code that runs on application startup
}
catch { }
// }
System.Data.SqlClient.SqlDependency.Start(connectionstring);
}
string user_id;
void worker_DoWork(ref int progress,
ref object _result, params object[] arguments)
{
// Do the operation every 1 second wihout the end.
while (true)
{
Random rand = new Random();
int randnum = rand.Next(5000, 20000);
Thread.Sleep(randnum);
// This statement will run every 1 second.
// string user_id = "";
// if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
// user_id = "22";// HttpContext.Current.Session["userId"].ToString();
user_id = ConfigurationManager.AppSettings["session_user_id"].ToString();
updatealarm(user_id);
}
// Other logic which you want it to keep running.
// You can do some scheduled tasks here by checking DateTime.Now.
}
}
AND
public class AlarmInfoRepository {
string connectionstr = ConfigurationManager.ConnectionStrings["officeConnectionString"].ConnectionString;
public IEnumerable GetData(string user_id)
{
using (SqlConnection connection = new SqlConnection(connectionstr))
{
//PersianCalendar jc = new PersianCalendar();
//string todayStr = jc.GetYear(DateTime.Now).ToString("0000") + "/" + jc.GetMonth(DateTime.Now).ToString("00") + "/" +
// jc.GetDayOfMonth(DateTime.Now).ToString("00");
//string timeStr = String.Format("{0:00}:{1:00}:{2:00}", jc.GetHour(DateTime.Now.AddSeconds(10)), jc.GetMinute(DateTime.Now.AddSeconds(10)), jc.GetSecond(DateTime.Now.AddSeconds(10)));
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT dbo.[web_alarmkartable].[id],dbo.[web_alarmkartable].peygir_id,dbo.[web_alarmkartable].user_id,
dbo.[web_alarmkartable].[content],dbo.[web_alarmkartable].[latestcreate_date],dbo.[web_alarmkartable].[latestcreate_time],
dbo.[web_alarmkartable].[firstcreate_date],dbo.[web_alarmkartable].[firstcreate_time],dbo.[web_alarmkartable].[duration],
dbo.[web_alarmkartable].[periodtype_id],dbo.[web_alarmkartable].[period],ISNULL(dbo.[web_alarmkartable].[color],'') AS color,dbo.[web_alarmkartable].id_tel FROM dbo.[web_alarmkartable] where dbo.[web_alarmkartable].content !='' AND dbo.[web_alarmkartable].content IS NOT NULL
AND (dbo.[web_alarmkartable].seen IS NULL OR dbo.[web_alarmkartable].seen =0) AND (dbo.[web_alarmkartable].expier IS NULL OR dbo.[web_alarmkartable].expier =0 )
AND (dbo.[web_alarmkartable].del=0 OR dbo.[web_alarmkartable].del IS NULL) AND dbo.[web_alarmkartable].user_id=" + user_id, connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new AlarmInfo()
{
id = x.GetInt32(0),
peygir_id = x.GetInt32(1),
user_id = x.GetInt32(2),
content = x.GetString(3),
latestcreate_date = x.GetString(4),
latestcreate_time = x.GetString(5),
firstcreate_date = x.GetString(6),
firstcreate_time = x.GetString(7),
duration = x.GetDecimal(8),
periodtype_id = x.GetInt32(9),
period = x.GetDecimal(10),
color = x.GetString(11),
id_tel = x.GetInt32(12)
}).ToList();
}
//if (connection.State == ConnectionState.Open)
// connection.Close();
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if ((e.Info.ToString() == "Insert" || e.Info.ToString() == "Update") && e.Type == SqlNotificationType.Change)
AlermHub.Show(e.Info.ToString());
}
}
AND
I use the fallowing method to update a contact in Exchange over EWS:
private void UpdateContact(Microsoft.Exchange.WebServices.Data.Contact exContact, ContactInfo contact) {
var pathList = new List<string>();
try {
log.DebugFormat("Process ExchangeContact '{0}' with Contact '{1}'", (exContact.IsNew ? "<new>" : exContact.DisplayName), contact.Id);
exContact.GivenName = contact.AdditionalName;
exContact.Surname = contact.Name;
exContact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
exContact.CompanyName = "";
if (contact is PersonInfo) {
var person = (PersonInfo) contact;
if (person.PersonCompany != null && person.PersonCompany.Company != null) {
exContact.CompanyName = person.PersonCompany.Company.DisplayName;
}
exContact.ImAddresses[ImAddressKey.ImAddress1] = person.MessengerName;
exContact.ImAddresses[ImAddressKey.ImAddress2] = person.SkypeName;
}
// Specify the business, home, and car phone numbers.
var comm = contact.GetCommunication(Constants.CommunicationType.PhoneBusiness);
exContact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhonePrivate);
exContact.PhoneNumbers[PhoneNumberKey.HomePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhoneMobile);
exContact.PhoneNumbers[PhoneNumberKey.MobilePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailBusiness);
exContact.EmailAddresses[EmailAddressKey.EmailAddress1] = (comm != null ? new EmailAddress(comm.Value) : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailPrivate);
exContact.EmailAddresses[EmailAddressKey.EmailAddress2] = (comm != null ? new EmailAddress(comm.Value) : null);
// Specify two IM addresses.
// Specify the home address.
var address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Private);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry;
if (contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Home;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = null;
}
address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Business);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry;
if(contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Business;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = null;
}
// Save the contact.
if (exContact.IsNew) {
exContact.Save();
} else {
exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
}
pathList.AddRange(this.AddFileAttachments(this.Access.IndependService.GetContact(exContact.Id.UniqueId), contact.GetDocuments()));
} catch(Exception e) {
log.Error("Error updating/inserting Contact in Exchange.", e);
} finally {
foreach (var path in pathList) {
this.Access.Context.Container.Resolve<IDocumentService>().UndoCheckOut(path);
}
}
}
When I do this for update, I get an Exception with Errorcode ErrorIncorrectUpdatePropertyCount on the line exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
Can someone help me, what is the problem? - Thanks.
The solution is that I have to check, if the string-values are empty strings and in this case to set null. On this way, all is working.