How to read event source name from EventLogRecord? - event-log

I am reading event log records as -
EventLogQuery query = new EventLogQuery(_eventLogName, PathType.LogName, sQuery);
query.ReverseDirection = true; // this tells it to start with newest first
List<EventRecord> eventRecords = new List<EventRecord>();
using (EventLogReader reader = new EventLogReader(query))
{
reader.BatchSize = 100;
EventRecord eventRecord;
while ((eventRecord = reader.ReadEvent()) != null)
{
if (_lastModified == null)
{
_lastModified = eventRecord.TimeCreated;
}
eventRecords.Add(eventRecord);
}
}
I am not sure how may i get Event Source value for each event.
Any help please...

Related

Error while Inserting data in loop pne by one using Entity Framework

while inserting records in a loop
The property "id" is part of the object's key information and cannot be modified
secProductionRepository.Add(tblSecProduction);
this.SaveChanges();
CODE
Controller : This is the Controller code from where i am calling method of Repository . Adding data into repository and calling function to insert. i think i have to initialize it every time with new keyword. But where should i do that.
SingleMaster objGetXMLData = _iSingleService.GetXMLData();
if (objGetXMLData._tblSecDoorXMLData != null)
{
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}
}
Repository : Here i am inserting new row into the table
public void UpdatetblSecDoorsProduction(tblSecDoorsProduction tblSecDoorsProduction, string Message)
{
var secDoorsProductionRepository = Nuow.Repository<tblSecDoorsProduction>();
tblSecDoorsProduction alreadyAttached = null;
if (Message == "Insert")
{
secDoorsProductionRepository.Add(tblSecDoorsProduction);
Nuow.SaveChanges();
}
}
Create new object each time in the loop. Updated code here:
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
tblSecDoorsProduction _tblSecDoorsProduction = new tblSecDoorsProduction();
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}

[Unity 5]matchmaking : matches not visible

I need your help please because I have an issue about matchmaking. I try to make a Pong playable online. When i use NetworkHUD, and I use Matchmaker, I can create a match, and the other app (on the same computer for now) detach it and can join it. But, when I don't use it, but I use matchmaker manually, I can create a match, I have a success response, I can find this match in the same app, but, in my second app, I can't find match created by the first app.
Can you help me?
Here are two functions in which I create match :
public void matchmaking()
{
nm.StartMatchMaker();
networkMatch.ListMatches(0, 20, "", OnMatchList);
Debug.LogError ("NBR MATCH " +matchList.Count);
if (matchList.Count == 0)
{
CreateMatchRequest match = new CreateMatchRequest();
match.name = "OrionPongRoom";
match.size = 2;
match.advertise = true;
match.password = "";
networkMatch.CreateMatch(match, OnMatchCreate);
}
else
Debug.Log ("******matches found"+matchList.Count);
}
void OnMatchCreate(CreateMatchResponse matchResponse)
{
if (matchResponse.success)
{
Debug.LogError("Create match succeeded");
matchCreated = true;
MatchInfo matchInfo = new MatchInfo(matchResponse);
Utility.SetAccessTokenForNetwork(matchResponse.networkId, new NetworkAccessToken(matchResponse.accessTokenString));
nm.StartHost(matchInfo);
NetworkServer.Listen(9000);
//NetworkServer.Listen(new MatchInfo(matchResponse), 9000);
}
else
{
Debug.LogError ("Create match failed");
}
}
You need to write
if (matchList.Count == 0)
{
CreateMatchRequest match = new CreateMatchRequest();
match.name = "OrionPongRoom";
match.size = 2;
match.advertise = true;
match.password = "";
networkMatch.CreateMatch(match, OnMatchCreate);
}
else
Debug.Log ("******matches found"+matchList.Count);
in OnMatchList method.
void OnMatchList(ListMatchResponse matchList)
{
if (matchList.Count == 0)
{
CreateMatchRequest match = new CreateMatchRequest();
match.name = "OrionPongRoom";
match.size = 2;
match.advertise = true;
match.password = "";
networkMatch.CreateMatch(match, OnMatchCreate);
}
else
Debug.Log ("******matches found"+matchList.Count);
}
Because of Network Delays etc, matchmaking server can not send response synchronous.

WP - How to constantly update my location

Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}

EF : related entities are set as INSERT instead of being only referenced to the added entity

I tried to find an answer through the related questions I got but I didn't see the same situation I have now. I a beginner with this framework.
The thing is that in the DB the TopicFeedbackType is always referred but TopicNavigatedUrl and Product are always inserted event if I attach the entity. What am I doing wrong? I attach the found entity to the correct entity set name. The entity gets attached. I noticed that before the p_TopicQuickFb have one of its property updated by an attached entity, its EntityKey is null, but when the currentNavUrl(for example) is set, the EntityKey of p_TopicQuickFb is not null anymore. Its value is "EntitySet=TopicQuickFeedbacks" but there is no id.
I am really lost in there.
public void AddTopicQuickFeedback(TopicQuickFeedback p_TopicQuickFb, string p_SessionID)
{
TopicFeedbackType currentType = this.GetTopicFeedbackType(p_TopicQuickFb.TopicFeedbackType.FeedbackType);
bool currentTypeAttached = false;
TopicNavigatedUrl currentNavUrl = this.GetTopicNavigatedUrl(p_TopicQuickFb.TopicNavigatedUrl.Url);
bool currentNavUrlAttached = false;
Product currentProduct = this.GetProduct(p_TopicQuickFb.Product.Name, p_TopicQuickFb.Product.MajorVersion, p_TopicQuickFb.Product.MinorVersion);
bool currentProductAttached = false;
using (COHFeedbackEntities context = GetObjectContext())
{
TopicFeedback tf = GetTopicFeedback(p_SessionID, context);
if (tf != null)
{
if (currentType != null)
{
p_TopicQuickFb.TopicFeedbackType = null;
context.AttachToOrGet<TopicFeedbackType>("TopicFeedbackTypes", ref currentType);
currentTypeAttached = true;
p_TopicQuickFb.TopicFeedbackType = currentType;
}
if (currentNavUrl != null)
{
p_TopicQuickFb.TopicNavigatedUrl = null;
context.AttachToOrGet<TopicNavigatedUrl>("TopicNavigatedUrls", ref currentNavUrl);
currentNavUrlAttached = true;
p_TopicQuickFb.TopicNavigatedUrl = currentNavUrl;
}
if (currentProduct != null)
{
p_TopicQuickFb.Product = null;
context.AttachToOrGet<Product>("Products", ref currentProduct);
currentProductAttached = true;
p_TopicQuickFb.Product = currentProduct;
}
tf.TopicQuickFeedbacks.Add(p_TopicQuickFb);
context.SaveChanges();
context.Detach(tf);
if (currentNavUrlAttached)
{
context.TopicNavigatedUrls.Detach(currentNavUrl);
}
if (currentProductAttached)
{
context.Products.Detach(currentProduct);
}
if (currentTypeAttached)
{
context.TopicFeedbackTypes.Detach(currentType);
}
}
}
}
I found the method in this post : Is is possible to check if an object is already attached to a data context in Entity Framework?
public static void AttachToOrGet<T>(this System.Data.Objects.ObjectContext context, string entitySetName, ref T entity)
where T : IEntityWithKey
{
System.Data.Objects.ObjectStateEntry entry;
// Track whether we need to perform an attach
bool attach = false;
if (
context.ObjectStateManager.TryGetObjectStateEntry
(
context.CreateEntityKey(entitySetName, entity),
out entry
)
)
{
// Re-attach if necessary
attach = entry.State == EntityState.Detached;
// Get the discovered entity to the ref
entity = (T)entry.Entity;
}
else
{
// Attach for the first time
attach = true;
}
if (attach)
{
context.AttachTo(entitySetName, entity);
}
}
Test method:
User user = new User(true, false, false);
string commentStr = "This is my comment";
Product product = new Product("ProductName", 7, 0);
TopicFeedbackComment commFeedback = new TopicFeedbackComment(commentStr, new TopicNavigatedUrl("http://testurl.com/test0"), product);
TopicFeedback feedback = new TopicFeedback(sessionID, user, FeedbackState.New);
provider.AddTopicFeedback(feedback);
TopicFeedback addedFeedback = provider.RetrieveTopicFeedback(sessionID);
provider.AddTopicFeedbackComment(commFeedback, sessionID);
Running this again and again do just INSERT to the
Can't post images so I can provide schema it if necessary.
My answer is in my last comment. I found it by myself.
If someone would like to comment why it's working this way it would be nice! :)

CRM 2011, Stopping custom workflow programmatically

i've been trying to stop a workflow programmatically.
I've read both in various posts and in the msdn that this can be done by updating
the Asyncoperation status via update request.
However everytime i update the request. the workflow get stuck on a mid stage such as cancelling or pausing and dosen't reach a final state.
any ideas?
protected void ExecutePostAccountUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
string fetchXML = "<fetch mapping='logical' count='50' version='1.0'>" +
"<entity name='asyncoperation'>" +
"<filter>" +
"<condition attribute='regardingobjectid' operator='eq' value='" +
localContext.PluginExecutionContext.PrimaryEntityId + "' />" +
"</filter>" +
"</entity>" +
"</fetch>";
EntityCollection col = localContext.OrganizationService.RetrieveMultiple(new FetchExpression(fetchXML));
if (col.Entities.Count > 0)
{
AsyncOperation a = (AsyncOperation)col[0];
a.StateCode = AsyncOperationState.Completed;
a.StatusCode = new OptionSetValue(32);
localContext.OrganizationService.Update(a);
}
}
Have a look at my blog: How to Cancel Workflow Programmatically using C#
Make sure the user have permissions to Cancel System Jobs.
QueryExpression queryExpression = new QueryExpression("asyncoperation") { ColumnSet = new ColumnSet("statuscode") };
queryExpression.Criteria.AddCondition("name", ConditionOperator.Equal, Name of Workflow);
queryExpression.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, regardingobjectId);
var asyncOperations = organizationService.RetrieveMultiple(queryExpression);
foreach (var asyncOperation in asyncOperations.Entities)
{
if (((OptionSetValue)asyncOperation["statuscode"]).Value == 10 || // Waiting
((OptionSetValue)asyncOperation["statuscode"]).Value == 20 || // In Process
((OptionSetValue)asyncOperation["statuscode"]).Value == 0)
{
Entity operation = new Entity("asyncoperation")
{
Id = asyncOperation.Id,
["statecode"] = new OptionSetValue(3),
["statuscode"] = new OptionSetValue(32)
};
organizationService.Update(operation);
}
}
Make sure the user have permissions to Cancel System Jobs.
It seems you can un-publish a workflow via code, according to this post.
NOTE: This does not necessarily halt an in-progress workflow, but it will prevent any new workflows of that type from being started.
const int WorkflowStatusDraft = 1;
const int WorkflowStatusPublished = 2;
public void PublishWorkflow(Guid workflowId)
{
SetStateWorkflowRequest publishRequest = new SetStateWorkflowRequest();
publishRequest.EntityId = workflowId;
publishRequest.WorkflowState = WorkflowState.Published;
publishRequest.WorkflowStatus = WorkflowStatusPublished;
this.CrmService.Execute(publishRequest);
}
public void UnpublishWorkflow(Guid workflowId)
{
SetStateWorkflowRequest unpublishRequest = new SetStateWorkflowRequest();
unpublishRequest.EntityId = workflowId;
unpublishRequest.WorkflowState = WorkflowState.Draft;
unpublishRequest.WorkflowStatus = WorkflowStatusDraft;
this.CrmService.Execute(unpublishRequest);
}