How can i get ram serial number? - c#-3.0

I need to know how I can get RAM (Physical memory) serial number. I am using C# and I used WMI to get Hardware information but serial Number return null on another computers. I want to know how can I get it and work on any computer (not WMI) and if there is no another way can I write it in C++ and make connection between this function and my application?
This is some of my code:
WqlObjectQuery Memory3_objectQuery = new WqlObjectQuery("Select * from Win32_PhysicalMemory");
ManagementObjectSearcher Memory3_Searcher = new ManagementObjectSearcher(Memory3_objectQuery);
foreach (ManagementObject MO2 in Memory3_Searcher.Get())
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Component_Type", "RAM");
try
{
Model = MO2["Model"].ToString();
if (Model != null)
{
cmd.Parameters.AddWithValue("#Model", Model);
}
else { }
}
catch (NullReferenceException) { }
try
{
Capacity = MO2["Capacity"].ToString();
if (Capacity != null)
{
cmd.Parameters.AddWithValue("#Capacity", Capacity);
}
else { }
}
catch (NullReferenceException)
{ }
try
{
Serial = MO2["SerialNumber"].ToString();
if (Serial != null)
{
cmd.Parameters.AddWithValue("#SerialNumber", Serial);
}
else { }
}
catch (NullReferenceException)
{
}
try
{
Manufacturer = MO2["Manufacturer"].ToString();
if (Manufacturer != null)
{
cmd.Parameters.AddWithValue("#Manufacturer", Manufacturer);
}
else { }
}
catch (NullReferenceException)
{
}
// Console.WriteLine("Serial Number Bank" + count + ": " + s);
try
{
s = MO2["MemoryType"].ToString();
if (s.Equals("21"))
{
s = "DDr2";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
else if (s.Equals("20"))
{
s = "DDr";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
else if (s.Equals("17"))
{
s = "SDRAM";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
}
catch (NullReferenceException) { }
cmd.Parameters.AddWithValue("#Computer_Name", myHost);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();

//SEE http://licensetoolkit.com/blog/hardware-identification-using-ram/
//using System.Management;
public static void OutputRamInformation()
{
// Create our WMI searcher to do our query
ManagementObjectSearcher searcher = new
ManagementObjectSearcher( "select * from Win32_PhysicalMemory" );
// Now loop through all the item found with the query
int ram = 1;
foreach ( ManagementObject obj in searcher.Get() )
{
Console.WriteLine( String.Format( "RAM #{0}:" , ram ) );
// Now step through each of the properties and output their values
foreach ( PropertyData property in obj.Properties )
{
if ( property.Value != null )
{
Console.WriteLine( property.Name + " = " +
property.Value.ToString() );
}
}
Console.WriteLine( "---------------------------------" );
// Increment our ram chip count
ram++;
}
// Wait for a keypress before continuting
Console.WriteLine( "Press any key to continue..." );
Console.ReadKey();
}

Related

opc ua milo - How to monitor an attribute under a node and return all the attributes of the node?

1、I need to monitor an attribute (eg: totalWp) in a node. If this attribute changes, I need to get all other attributes (PT...) under this node. My code cannot get the expected result, please tell Me, what should I do?
protected CompletableFuture<UaSubscription> createValueSubscription(String deviceId) {
final CompletableFuture<UaSubscription> result = new CompletableFuture<>();
try {
Node node = this.getDeviceNode(deviceId);
NodeId parentId = node.getNodeId().get();
UaSubscriptionManager subscriptionManager = this.getOpcUaClient().getSubscriptionManager();
CompletableFuture<UaSubscription> subscriptionFuture = subscriptionManager.createSubscription(5000.0);
subscriptionFuture.whenComplete((subscription, e) -> {
if (e != null) {
result.completeExceptionally(e);
} else {
subscription.addNotificationListener(new UaSubscription.NotificationListener() {
#Override
public void onDataChangeNotification(UaSubscription subscription, List<UaMonitoredItem> monitoredItems, List<DataValue> dataValues, DateTime publishTime) {
Iterator<UaMonitoredItem> itemIterator = monitoredItems.iterator();
Iterator<DataValue> dataValueIterator = dataValues.iterator();
while (itemIterator.hasNext() && dataValueIterator.hasNext()) {
logger.info("--- subscription value received: item= " + itemIterator.next().getReadValueId().getNodeId()
+ ", value=" + dataValueIterator.next().getValue() + " ---");
}
}
});
NodeId valueId = OpcUaClientUtils.createDeviceAttributeId(parentId, "totalWp");
NodeId pt = OpcUaClientUtils.createDeviceAttributeId(parentId, "PT");
ReadValueId readTotalWpId = new ReadValueId(valueId, AttributeId.Value.uid(), null, null);
ReadValueId readPtId = new ReadValueId(pt, AttributeId.Value.uid(), null, null);
UInteger clientHandle = uint(clientHandles.getAndIncrement());
MonitoringParameters parameters = new MonitoringParameters(
clientHandle,
1000.0, // sampling interval
null, // filter, null means use default
Unsigned.uint(10), // queue size
true // discard oldest
);
MonitoredItemCreateRequest requestTotalWp = new MonitoredItemCreateRequest(readTotalWpId, MonitoringMode.Reporting, parameters);
MonitoredItemCreateRequest requestPt = new MonitoredItemCreateRequest(readPtId, MonitoringMode.Reporting, parameters);
// requests.add(requestPt);
CompletableFuture<List<UaMonitoredItem>> future =
subscription.createMonitoredItems(
TimestampsToReturn.Both,
newArrayList(requestTotalWp),
(item, id) -> onValueChanged(deviceId, item, id)
);
future.whenComplete((items, ex) -> {
if (ex == null) {
result.complete(subscription);
} else {
result.completeExceptionally(ex);
}
});
} ;
});
} catch (Exception e) {
result.completeExceptionally(e);
}
return result;
}
The above code only returns the monitored attributes, other attributes are not returned.
You are only creating 1 MonitoredItem:
CompletableFuture<List<UaMonitoredItem>> future =
subscription.createMonitoredItems(
TimestampsToReturn.Both,
newArrayList(requestTotalWp),
(item, id) -> onValueChanged(deviceId, item, id)
);
If you want to receive changes for other Nodes then you need to create MonitoredItems for them as well.

when I pushed the phone button to back previous page in Unity webviewScript

using System.Collections;
using UnityEngine;
using System;
using System.Collections.Generic;
public class SampleWebView : MonoBehaviour
{
public string Url;
public GUIText status;
WebViewObject webViewObject;
IEnumerator Start()
{
webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
webViewObject.Init(
cb: (msg) =>
{
Debug.Log(string.Format("CallFromJS[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
err: (msg) =>
{
Debug.Log(string.Format("CallOnError[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
started: (msg) =>
{
Debug.Log(string.Format("CallOnStarted[{0}]", msg));
},
ld: (msg) =>
{
Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
// NOTE: depending on the situation, you might prefer
// the 'iframe' approach.
// cf. https://github.com/gree/unity-webview/issues/189
#if true
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
window.location = 'unity:' + msg;
}
}
}
");
#else
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'unity:' + msg);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}
}
");
#endif
#endif
webViewObject.EvaluateJS(#"Unity.call('ua=' + navigator.userAgent)");
},
//ua: "custom user agent string",
enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
webViewObject.bitmapRefreshCycle = 1;
#endif
webViewObject.SetMargins(10, 140, 10, Screen.height / 360);
webViewObject.SetVisibility(true);
#if !UNITY_WEBPLAYER
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
var exts = new string[]{
".jpg",
".js",
".html" // should be last
};
foreach (var ext in exts) {
var url = Url.Replace(".html", ext);
var src = System.IO.Path.Combine(Application.streamingAssetsPath, url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, url);
byte[] result = null;
if (src.Contains("://")) { // for Android
var www = new WWW(src);
yield return www;
result = www.bytes;
} else {
result = System.IO.File.ReadAllBytes(src);
}
System.IO.File.WriteAllBytes(dst, result);
if (ext == ".html") {
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
break;
}
}
}
#else
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
}
webViewObject.EvaluateJS(
"parent.$(function() {" +
" window.Unity = {" +
" call:function(msg) {" +
" parent.unityWebView.sendMessage('WebViewObject', msg)" +
" }" +
" };" +
"});");
#endif
yield break;
}
#if !UNITY_WEBPLAYER
//void OnGUI()
//{
// GUI.enabled = webViewObject.CanGoBack();
// if (GUI.Button(new Rect(10, 10, 80, 80), "<")) {
// webViewObject.GoBack();
// }
// GUI.enabled = true;
// GUI.enabled = webViewObject.CanGoForward();
// if (GUI.Button(new Rect(100, 10, 80, 80), ">")) {
// webViewObject.GoForward();
// }
// GUI.enabled = true;
// GUI.TextField(new Rect(200, 10, 300, 80), "" + webViewObject.Progress());
//}
#endif
This is my webview Scirpt for my newspaper App in C#. I need code, when I pushed the phone button to go back previous page in the newspaper.
I tried,
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
However it quits from the app. It does not go back previous page in the newspaper..
Thank you for your help...
if i understand it correctly you should be good if you replace
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
by this:
if(Input.GetKeyDown(KeyCode.Escape))
{
webViewObject.GoBack();
}
According to the example you are using from here https://github.com/gree/unity-webview/blob/master/sample/Assets/Scripts/SampleWebView.cs this is the build in back function. You can see it in the commented out part in your code.

mybatis interceptor sql log process

i make mybatis sqllog intercepor in my project.
in case. #{__frch_CUST_0} #{__frch_CUST_1} ~~~ #{__frch_CUST_N}
how can i get parameters value "__frch_CUST_n" ?
// mybatis interceptor sql log function
public String getSqlLog(StatementHandler handler)
{
String sql = handler.getBoundSql().getSql();
Object param = handler.getParameterHandler().getParameterObject();
List<ParameterMapping> paramMapping = handler.getBoundSql().getParameterMappings();
// change \? value to replace point
for(ParameterMapping mapping:paramMapping)
{
sql = sql.replaceFirst("\\?", "#{"+mapping.getProperty()+"}");
}
for(ParameterMapping mapping:paramMapping)
{
String sqlparam = "#{"+mapping.getProperty()+"}";
String sqlparamname = mapping.getProperty();
Object sqlparamvalue = ((Map) param).get(sqlparamname);
if( !sqlparamname.startsWith("__frch_") )
{
if(isNull(sqlparamvalue))
{
sql = sql.replace(sqlparam, "NULL");
}
else
{
if(sqlparamvalue instanceof String)
{
try
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
catch(Exception e)
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
}
else
{
sql = sql.replace(sqlparam, sqlparamvalue.toString());
}
}
}
else
{
**// HOW CAN I DO HERE?**
}
}
return sql;
}
thank you for read my question..
i resolve my self.
mybatis make new arrayList parameter. and use it.
example list value
DATE = ['20180101','20180102','20180103'];
STEP = ['PLAN', 'MAKE', 'SETUP'];
__frch_DATE_0
__frch_DATE_1
__frch_DATE_2
__frch_STEP_3
__frch_STEP_4
__frch_STEP_5
mybatis __frch_ = ['20180101','20180102','20180103','PLAN', 'MAKE', 'SETUP']
so i use it. my question is resolved..
public String getSqlLog(StatementHandler handler)
{
String sql = handler.getBoundSql().getSql();
Object param = handler.getParameterHandler().getParameterObject();
List<ParameterMapping> paramMapping = handler.getBoundSql().getParameterMappings();
List foreachlist = new ArrayList();
for(ParameterMapping mapping:paramMapping)
{
sql = sql.replaceFirst("\\?", "#{"+mapping.getProperty()+"}");
}
for(ParameterMapping mapping:paramMapping)
{
String sqlparam = "#{"+mapping.getProperty()+"}";
String sqlparamname = mapping.getProperty();
Object sqlparamvalue = ((Map) param).get(sqlparamname);
if( !sqlparamname.startsWith("__frch_") )
{
if(isNull(sqlparamvalue))
{
sql = sql.replace(sqlparam, "NULL");
}
else
{
if(sqlparamvalue instanceof String)
{
try
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
catch(Exception e)
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
}
else
{
sql = sql.replace(sqlparam, sqlparamvalue.toString());
}
}
}
else
{
if( foreachlist.size() == 0 )
{
Map parammap = (Map)param;
Iterator iterator = parammap.keySet().iterator();
while(iterator.hasNext())
{
String key = iterator.next().toString();
Object value = (Object)parammap.get(key);
if( value instanceof List )
{
List valuelist = (List)value;
for(int i=0;i<valuelist.size();i++)
{
foreachlist.add(valuelist.get(i));
}
}
}
}
String buff = sqlparamname.split("__frch_")[1];
int index = Integer.parseInt(buff.substring(buff.lastIndexOf("_")+1));
try
{
sql = sql.replace(sqlparam, "'"+getSQLString((String)foreachlist.get(index))+"'");
}
catch(Exception e)
{
;
}
}
}
return sql;
}

opcua session was closed by client

I have written the attached OpcUaConnector class for opc-ua connection related activities.
But it is not handling session. For example:
In opc ua configuration disabled the endpoint
In kepserver configuration did runtime > reinitializing
The windows service is throwing:
Source : system.Reactive.Core
InnerException : The session was closed by client
and stopping the windows service, as this error goes unhandled.
Can some one suggest how to handle session in opc-ua?
public class OpcUaConnector
{
private static SimplerAES simplerAES = new SimplerAES();
private DataContainer dataCointainer = null;
private UaTcpSessionChannel channel;
private string opcServerName = string.Empty;
private string opcUserId = string.Empty;
private string opcPassword = string.Empty;
private static ILog LogOpcStore;
private static System.IDisposable token;
private static uint id;
public OpcConnector(ILog Log)
{
IntializeLogOpcStore(Log);
}
private static void IntializeLogOpcStore(ILog Log)
{
LogOpcStore = Log;
}
public async Task OpenOpcConnection()
{
try
{
if ((!string.IsNullOrEmpty(this.opcServerName) & (this.opcServerName != AppMain.MyAppSettings.OpcServer)) ||
(!string.IsNullOrEmpty(this.opcUserId) & (this.opcUserId != AppMain.MyAppSettings.OpcUserId)) ||
(!string.IsNullOrEmpty(this.opcPassword) & (this.opcPassword != AppMain.MyAppSettings.OpcPassword)))
{
await channel.CloseAsync();
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
if (channel==null || (channel != null && (channel.State == CommunicationState.Closed || channel.State == CommunicationState.Faulted)))
{
var appDescription = new ApplicationDescription()
{
ApplicationName = "MyAppName",
ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:MyAppName",
ApplicationType = ApplicationType.Client,
};
//application data won't be deleted when uninstall
var certificateStore = new DirectoryStore(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyAppName", "pki"),
true, true
);
//if the Ethernet cable unplugs or the Wifi drops out,
//you have some timeouts that can keep the session open for a while.
//There is a SessionTimeout (default of 2 min).
this.channel = new UaTcpSessionChannel(
appDescription,
certificateStore,
SignInOpc,
AppMain.MyAppSettings.OpcServer,
null,
options: new UaTcpSessionChannelOptions { SessionTimeout = 120000 });
await channel.OpenAsync();
//LogOpcStore.Info(String.Format("Opc connection sucessful"));
}
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.HResult + " " + ex.Message, "C052");
throw serviceException;
}
}
private static async Task RecursivelyFindNode(UaTcpSessionChannel channel, NodeId nodeid)
{
BrowseRequest browseRequest = new BrowseRequest
{
NodesToBrowse = new BrowseDescription[] { new BrowseDescription { NodeId = nodeid, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } },
};
BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);
foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0])
{
uint chid = AppMain.MyTagDatabase.GetClientHandleByTag(rd1.DisplayName.ToString());
if (chid > 0)
{
AppMain.MyTagDatabase.UpdateNodeByClientHandle(chid, rd1.NodeId.ToString());
}
await RecursivelyFindNode(channel, ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris));
}
}
public async Task CreateSubscription(DataContainer dc)
{
double curReadingValue;
try
{
dataCointainer = dc;
await RecursivelyFindNode(channel, NodeId.Parse(ObjectIds.RootFolder));
if (AppMain.MyTagDatabase.GetCntTagsNotInOpcServer() == AppMain.MyTagDatabase.GetTagCount())
{
//no need to create subscription
return;
}
//subscription timeout that is the product of PublishingInterval * LifetimeCount:
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest);
id = subscriptionResponse.SubscriptionId;
var itemsToCreate = new MonitoredItemCreateRequest[AppMain.MyTagDatabase.GetTagHavingNodeCount()];
int i = 0;
foreach (var item in AppMain.MyTagDatabase.GetMyTagDatabase())
{
var itemKey = item.Key;
var itemValue = item.Value;
itemsToCreate[i] = new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse(itemValue.NodeId), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = itemKey, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } };
i++;
}
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = itemsToCreate,
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
}
catch (Exception ex)
{
//If the interruption lasts longer than these timeouts then the SessionChannel and Subscriptions will need to be recreated.
channel = null;
FatalServiceException fatalserviceException = new FatalServiceException(ex.Message, "C052");
throw fatalserviceException;
}
}
public async Task DeleteSubscription()
{
try
{
var request = new DeleteSubscriptionsRequest
{
SubscriptionIds = new uint[] { id }
};
await channel.DeleteSubscriptionsAsync(request);
token.Dispose();
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.Message, "C052");
throw serviceException;
}
}
private static async Task<IUserIdentity> SignInOpc(EndpointDescription endpoint)
{
IUserIdentity userIdentity = null;
if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
{
userIdentity = new AnonymousIdentity();
}
else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
{
var userName = AppMain.MyAppSettings.OpcUserId;
var password = simplerAES.Decrypt(AppMain.MyAppSettings.OpcPassword);
userIdentity = new UserNameIdentity(userName, password);
}
return userIdentity;
}
private void AddDataPointToContainer(int dataType, string source, DateTime SourceTimestampUTC, double value)
{
ConditionValue conditionValue = new ConditionValue();
long timestamp = AppMain.ServerSyncTimeStore.ConvertDateTimeToTimeStampUTC(SourceTimestampUTC);
conditionValue.dataType = dataType;
conditionValue.source = source;
conditionValue.timestamp = timestamp;
conditionValue.SourceTimestampUTC = SourceTimestampUTC;
conditionValue.LocalTime = SourceTimestampUTC.ToLocalTime();
conditionValue.value = value;
//LogOpcStore.Info(String.Format("TagName : {0} SourceTimestampUTC : {1} timestamp : {2} LocalTime : {3} curReadingValue : {4}", source, SourceTimestampUTC, timestamp, SourceTimestampUTC.ToLocalTime(), value));
dataCointainer.AddDataPoint(conditionValue);
}
}
I see you are using the project https://github.com/convertersystems/opc-ua-client.
When a server closes the session and socket (as happens when you reinitialize Kepware) the client receives immediate notification that causes the client channel to fault. A faulted channel cannot be reopened, it should be aborted and a new channel should be created.
I made this standalone test, to show that you may have to catch an exception and recreate the channel and subscription. The point of this test is to subscribe to the CurrentTime node and collect 60 datachanges. The test should last a minute. If you re-init the Kepware server in the middle of the test, the code catches the exception and recreates the channel and subscription.
[TestMethod]
public async Task OpcConnectorTest()
{
var count = 0;
UaTcpSessionChannel channel = null;
while (count < 60)
{
try
{
channel = new UaTcpSessionChannel(
this.localDescription,
this.certificateStore,
new AnonymousIdentity(),
EndpointUrl,
SecurityPolicyUris.None,
loggerFactory: this.loggerFactory);
await channel.OpenAsync();
// create the keep alive subscription.
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);
var id = subscriptionResponse.SubscriptionId;
var token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
Console.WriteLine($"sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}");
count++;
}
}
});
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = new MonitoredItemCreateRequest[]
{
new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } }
},
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
while (channel.State == CommunicationState.Opened && count < 60)
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.GetType()}. {ex.Message}");
}
}
if (channel != null)
{
Console.WriteLine($"Closing session '{channel.SessionId}'.");
await channel.CloseAsync();
}
}
I know this is an old post, but I stumbled upon this problem as well. For those interested:
The problem is related to the subscription(s).
When the following code is run:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
Observable.subscribe() takes multiple arguments. You should include what to do in case of an error. For example:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(
pr => { code to run normally... },
ex => { Log.Info(ex.Message); },
() => { }
);
See http://reactivex.io/documentation/operators/subscribe.html for more information.

video overwriting using ffmpeg - I want to Add video rotation code and rewrite the existing file..How can i do that?

I want to rotate the .mov file which is in portrait mode by 90 degrees, for that i used the following code..
It works but, it results in loss of video frames...
My code is,
public void encode(File source, File target, EncodingAttributes attributes,
EncoderProgressListener listener, Integer i) throws IllegalArgumentException,
InputFormatException, EncoderException {
String formatAttribute = attributes.getFormat();
Float offsetAttribute = attributes.getOffset();
Float durationAttribute = attributes.getDuration();
QualityScale qualityScale = attributes.getQualityScale();
AudioAttributes audioAttributes = attributes.getAudioAttributes();
VideoAttributes videoAttributes = attributes.getVideoAttributes();
if (audioAttributes == null && videoAttributes == null) {
throw new IllegalArgumentException(
"Both audio and video attributes are null");
}
target = target.getAbsoluteFile();
target.getParentFile().mkdirs();
FFMPEGExecutor ffmpeg = locator.createExecutor();
if (offsetAttribute != null) {
ffmpeg.addArgument("-ss");
ffmpeg.addArgument(String.valueOf(offsetAttribute.floatValue()));
}
ffmpeg.addArgument("-i");
ffmpeg.addArgument(source.getAbsolutePath());
if (durationAttribute != null) {
ffmpeg.addArgument("-t");
ffmpeg.addArgument(String.valueOf(durationAttribute.floatValue()));
}
if (qualityScale != null) {
ffmpeg.addArgument("-qscale:"+qualityScale.getQualityStreamSpecifier());
ffmpeg.addArgument(String.valueOf(qualityScale.getQualityValue()));
}
if (videoAttributes == null) {
ffmpeg.addArgument("-vn");
} else {
String codec = videoAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-vcodec");
ffmpeg.addArgument(codec);
}
String tag = videoAttributes.getTag();
if (tag != null) {
ffmpeg.addArgument("-vtag");
ffmpeg.addArgument(tag);
}
Integer bitRate = videoAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-b");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer frameRate = videoAttributes.getFrameRate();
if (frameRate != null) {
ffmpeg.addArgument("-r");
ffmpeg.addArgument(String.valueOf(frameRate.intValue()));
}
VideoSize size = videoAttributes.getSize();
if (size != null) {
ffmpeg.addArgument("-s");
ffmpeg.addArgument(String.valueOf(size.getWidth()) + "x"
+ String.valueOf(size.getHeight()));
}
FilterGraph filterGraph = videoAttributes.getFilterGraph();
if (filterGraph != null) {
ffmpeg.addArgument("-vf");
if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 90){
ffmpeg.addArgument("transpose=1");
}else if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 180){
ffmpeg.addArgument("vflip,hflip");
}
else {
if (filterGraph.isUseExpression()) {
ffmpeg.addArgument(filterGraph.getFilterGraphExpression());
}
}
}
}
if (audioAttributes == null) {
ffmpeg.addArgument("-an");
} else {
String codec = audioAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-acodec");
ffmpeg.addArgument(codec);
}
Integer bitRate = audioAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-ab");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer channels = audioAttributes.getChannels();
if (channels != null) {
ffmpeg.addArgument("-ac");
ffmpeg.addArgument(String.valueOf(channels.intValue()));
}
Integer samplingRate = audioAttributes.getSamplingRate();
if (samplingRate != null) {
ffmpeg.addArgument("-ar");
ffmpeg.addArgument(String.valueOf(samplingRate.intValue()));
}
Integer volume = audioAttributes.getVolume();
if (volume != null) {
ffmpeg.addArgument("-vol");
ffmpeg.addArgument(String.valueOf(volume.intValue()));
}
}
ffmpeg.addArgument("-f");
ffmpeg.addArgument(formatAttribute);
ffmpeg.addArgument("-y");
ffmpeg.addArgument(target.getAbsolutePath());
try {
ffmpeg.execute();
} catch (IOException e) {
throw new EncoderException(e);
}
try {
String lastWarning = null;
long duration;
long progress = 0;
RBufferedReader reader = null;
reader = new RBufferedReader(new InputStreamReader(ffmpeg
.getErrorStream()));
MultimediaInfo info = parseMultimediaInfo(source, reader);
if (durationAttribute != null) {
duration = (long) Math
.round((durationAttribute.floatValue() * 1000L));
} else {
duration = info.getDuration();
if (offsetAttribute != null) {
duration -= (long) Math
.round((offsetAttribute.floatValue() * 1000L));
}
}
if (listener != null) {
listener.sourceInfo(info);
}
int step = 0;
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line::::"+line);
if (step == 0) {
if (line.startsWith("WARNING: ")) {
if (listener != null) {
listener.message(line);
}
} else if (!line.startsWith("Output #0")) {
//throw new EncoderException(line);
} else {
step++;
}
} else if (step == 1) {
if (!line.startsWith(" ")) {
step++;
} else {
System.out.println("line>>>>>>"+line);
Hashtable table1 = new Hashtable();
Matcher m = ROTATE_INFO_PATTERN.matcher(line);
while (m.find()) {
if (table1 == null) {
table1 = new Hashtable();
}
String key = m.group(1);
String value = m.group(2);
table1.put(key, value);
}
System.out.println("Table values"+table1.get("rotate"));
if(table1.get("rotate") != null){
Object videoRotateValue = table1.get("rotate");
int rotate = Integer.valueOf(videoRotateValue.toString());
switch(rotate){
case 90:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 180:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 270: System.out.println("case 3 :: "+videoRotateValue);
break;
}
}
}
}
if (step == 2) {
if (!line.startsWith("Stream mapping:")) {
throw new EncoderException(line);
} else {
step++;
}
} else if (step == 3) {
if (!line.startsWith(" ")) {
step++;
}
}
if (step == 4) {
line = line.trim();
if (line.length() > 0) {
Hashtable table = parseProgressInfoLine(line);
if (table == null) {
if (listener != null) {
listener.message(line);
}
lastWarning = line;
} else {
if (listener != null) {
String time = (String) table.get("time");
if (time != null) {
int dot = time.indexOf('.');
if (dot > 0 && dot == time.length() - 2
&& duration > 0) {
String p1 = time.substring(0, dot);
String p2 = time.substring(dot + 1);
try {
long i1 = Long.parseLong(p1);
long i2 = Long.parseLong(p2);
progress = (i1 * 1000L)
+ (i2 * 100L);
int perm = (int) Math
.round((double) (progress * 1000L)
/ (double) duration);
if (perm > 1000) {
perm = 1000;
}
listener.progress(perm);
} catch (NumberFormatException e) {
;
}
}
}
}
lastWarning = null;
}
}
}
}
if (lastWarning != null) {
if (!SUCCESS_PATTERN.matcher(lastWarning).matches()) {
throw new EncoderException(lastWarning);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ffmpeg.destroy();
}
}
Please advise, how to achieve video rotation without any video Frame loss
Thanks In Advance
Lakshmi Priya . K
Worked for couple of days and finally tried to write the rotated video in different target file then i got the video output without any loss and video is also rotated....
Thanks
Lakshmi Priya. K