F#: DataContractJsonSerializer.WriteObject method - json

I am new to programming and F# is my first language.
Here are the relevant parts of my code:
let internal saveJsonToFile<'t> (someObject:'t) (filePath: string) =
use fileStream = new FileStream(filePath, FileMode.OpenOrCreate)
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(fileStream, someObject)
let dummyFighter1 = { id = 1; name = "Dummy1"; location = "Here"; nationality = "Somalia"; heightInMeters = 2.0; weightInKgs = 220.0; weightClass = "Too fat"}
let dummyFighter2 = { id = 2; name = "Dummy2"; location = "There"; nationality = "Afghanistan"; heightInMeters = 1.8; weightInKgs = 80.0; weightClass = "Just Nice"}
let filePath = #"G:\User\Fighters.json"
saveJsonToFile dummyFighter1 filePath
saveJsonToFile dummyFighter2 filePath
When I run "saveJsonToFile dummyFighter1 filePath", the information is successfully saved. My problem is this: Once I run "saveJsonToFile dummyFighter2 filePath", it immediately replaces all the contents that are already in the file, i.e., all the information about dummyFighter1.
What changes should I make so that information about dummyFighter2 is appended to the file, instead of replacing information about dummyFighter1?

Change the way you open a file setting FileMode.OpenOrCreate to FileMode.Append. Append means "create or append" :
use fileStream = new FileStream(filePath, FileMode.Append)
From MSDN (https://msdn.microsoft.com/fr-fr/library/system.io.filemode%28v=vs.110%29.aspx) :
FileMode.Append opens the file if it exists and seeks to the end of the file, or
creates a new file. This requires FileIOPermissionAccess.Append
permission. FileMode.Append can be used only in conjunction with
FileAccess.Write. Trying to seek to a position before the end of the
file throws an IOException exception, and any attempt to read fails
and throws a NotSupportedException exception.

Related

How to search registered user on ejabberd server from client side using smack library?

I am using smack on the client-side. I tried to search registered users on the client-side because before creating a new user I want to know that the id is registered on server or not if not then create the user either log in the user but ejabberd server crashed with the error. Here are the crash logs of ejabberd server.
Failed to process iq:
#iq{
id = <<"Hh6AJ-28">>,type = set,lang = <<"en">>,
from =
#jid{
user = <<"admin">>,server = <<"faiqkhan-virtualbox">>,
resource = <<"92526029764259513741138">>,luser = <<"admin">>,
lserver = <<"faiqkhan-virtualbox">>,
lresource = <<"92526029764259513741138">>},
to =
#jid{
user = <<>>,server = <<"vjud.faiqkhan-virtualbox">>,resource = <<>>,
luser = <<>>,lserver = <<"vjud.faiqkhan-virtualbox">>,lresource = <<>>},
sub_els =
[#xmlel{
name = <<"query">>,
attrs = [{<<"xmlns">>,<<"jabber:iq:search">>}],
children =
[#xmlel{
name = <<"x">>,
attrs = [{<<"xmlns">>,<<"jabber:x:data">>},{<<"type">>,<<"submit">>}],
children =
[#xmlel{
name = <<"field">>,
attrs = [{<<"var">>,<<"user">>},{<<"type">>,<<"text-single">>}],
children =
[#xmlel{
name = <<"value">>,attrs = [],
children = [{xmlcdata,<<"wasiq#faiqkhan-virtualbox">>}]}]}]}]}],
meta = #{ip => {0,0,0,0,0,65535,49320,11092}}}
exception error: {module_not_loaded,mod_vcard_mnesia,
<<"faiqkhan-virtualbox">>}
in function gen_mod:get_module_opts/2 (src/gen_mod.erl, line 338)
in call from gen_mod:get_module_opt/3 (src/gen_mod.erl, line 318)
in call from mod_vcard_mnesia:filter_fields/3 (src/mod_vcard_mnesia.erl, line 200)
in call from mod_vcard_mnesia:search/4 (src/mod_vcard_mnesia.erl, line 78)
in call from mod_vcard:search_result/4 (src/mod_vcard.erl, line 479)
in call from mod_vcard:process_search/1 (src/mod_vcard.erl, line 264)
in call from gen_iq_handler:process_iq/3 (src/gen_iq_handler.erl, line 131)
in call from gen_iq_handler:process_iq/4 (src/gen_iq_handler.erl, line 109)
I used the following code to get a registered user from the client-side:
InetAddress address = InetAddress.getByName(HOST);
DomainBareJid serviceName = JidCreate.domainBareFrom("faiqkhan-VirtualBox"); XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setPort(PORT);
builder.setSendPresence(true);
builder.setHostAddress(address);
builder.setServiceName(serviceName);
builder.setUsernameAndPassword("admin", "123456");
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());
try {
connection.connect();
connection.login("admin", "123456");
Logger.showError("21560-connection created to: " + connection.getHost());
Roster roster = Roster.getInstanceFor(connection);
Set<RosterEntry> entities = roster.getEntries();
UserSearchManager search = new UserSearchManager(connection);
DomainBareJid s = JidCreate.domainBareFrom("vjud.".concat("faiqkhan-VirtualBox"));
Form searchForm = search.getSearchForm(s);
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("user", "wasiq#faiqkhan-virtualbox");
ReportedData data = search.getSearchResults(answerForm, s);
if (data.getRows() != null) {
for (ReportedData.Row row : data.getRows()) {
for (CharSequence value : row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
}
} catch (SmackException | IOException | XMPPException | InterruptedException e) {
Logger.showError("21560-error on account creation: " + e.getMessage());
}
Server crashed on ReportedData data = search.getSearchResults(answerForm, s); line of code.
You found a bug in ejabberd:
It was already fixed in 2018 in
https://github.com/processone/ejabberd/commit/1be21126342d503205798605725ba5ceef9de42b
but the bug got reintroduced in 2019 in
https://github.com/processone/ejabberd/commit/a02cff0e780bb735531594c4ece81e8628f79782#diff-71f613241ed580c3e5dad2b4526503f2R12
and I've now applied a temporary fix in
https://github.com/processone/ejabberd/commit/92913389a51ddc564f11e0712b0d82fca8c9aecb
But even if that bug is fixed, the feature you want to use probably doesn't help: a user must set his vCard in order for his account to be provided in vJud search. In other words, vJUD searches in stored vCards, not in registered accounts. If I register an account but don't set a vCard, then vJUD will not find it.
before creating a new user I want to know that the id is registered on server or not
And why don't you simply attempt to register the account first?
On the other hand, if you would like to check in advance if an account is available for registration or not (like some web registration sites do, to allow the user modify the username until one is available), then I think XMPP doesn't provide that possibility for security reasons: it is not allowed to know if an account exists or not.
A solution for that would be to use the check_account ejabberd command
https://docs.ejabberd.im/developer/ejabberd-api/admin-api/#check-account
executing it with some frontend, like ejabberdctl, ReST or XMLRPC
https://docs.ejabberd.im/admin/guide/managing/#ejabberd-commands
$ ejabberdctl check_account user1 localhost
$ ejabberdctl check_account user6666 localhost
Error: false
~ 1

Getting PidLidEndRecurrenceDate value using Ews

What is the correct way of getting PidLidEndRecurrenceDate values using Ews. below code does not give proper result. property details that i am looking is https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/816378cf-07ef-4926-b7d2-53475792403d
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("X#X.com", "XXX");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ItemView view = new ItemView(10);
Guid MyPropertySetId = new Guid("{6ED8DA90-450B-101B-98DA-00AA003F1305}");
int intValue = Convert.ToInt32("0x0000000F", 16);
ExtendedPropertyDefinition extendedPropertyDefinition =
new ExtendedPropertyDefinition(MyPropertySetId, intValue, MapiPropertyType.Integer);
view.PropertySet =
new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, extendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Calendar, view);
foreach (Item item in findResults.Items)
{
Console.WriteLine(item.Subject);
if (item.ExtendedProperties.Count > 0)
{
// Display the extended name and value of the extended property.
foreach (ExtendedProperty extendedProperty in item.ExtendedProperties)
{
Console.WriteLine(" Extended Property Name: " + extendedProperty.PropertyDefinition.Name);
Console.WriteLine(" Extended Property Value: " + extendedProperty.Value);
}
}
}
That property is set on the Meeting invite messages only not on the Master instance of the Calendar Appointments which is what you seem to be looking at. For the Master instances you should just be able to use the strongly typed property https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.recurrence.enddate?redirectedfrom=MSDN&view=exchange-ews-api#Microsoft_Exchange_WebServices_Data_Recurrence_EndDate
It you wanted to view the property you have above search the SentItems Folder for invites with recurrences (with Enddates) and that's where you will see it. Or probably easier just look at the messages with a Mapi editor like OutlookSpy or MFCMAPI and you will see the properties available.

saving image into database which is generated dynamically and saved in image button

Random rd = new Random();
string data = rd.Next(111111111, 999999999).ToString();
QRCodeGenerator q = new QRCodeGenerator();
QRCodeGenerator.QRCode qc = q.CreateQrCode(data,
QRCodeGenerator.ECCLevel.Q);
System.Drawing.Bitmap bm = qc.GetGraphic(28);
MemoryStream ms = new MemoryStream();
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] b = ms.ToArray();
Image1.ImageUrl = "data:image/png;base64," + `Convert.ToBase64String(b);`
String qr = Image1.ImageUrl.ToString();
i have generated qr code and put into imagebox i need to save it to sql database in asp.net
I think you don't want to save the actual image in the db, just the link to it:
Random rd = new Random();
string Path="D:\data\images\"; //folder where you want to store images
string data = rd.Next(111111111, 999999999).ToString();
QRCodeGenerator q = new QRCodeGenerator();
QRCodeGenerator.QRCode qc = q.CreateQrCode(data,
QRCodeGenerator.ECCLevel.Q);
System.Drawing.Bitmap bm = qc.GetGraphic(28);
Guid uniqueid=new Guid();
bm.Save(path+uniqueid.ToString()+'.png', System.Drawing.Imaging.ImageFormat.Png);
You only save the link to this file in the DB
(the path and the file name to this png file) as well as an identifier that you will query to get this link.
You need to create a table in the database, add the fields needed
(once you do this I could help you further with inserting the record in the db)
First create a database in SQL, like this:
CREATE DATABASE QRDataBaseEntities
GO
CREATE TABLE Photo
(
PhotoID INT IDENTITY PRIMARY KEY,
Name NVARCHAR(100),
Photo VARBINARY(MAX)
)
Then create a function in C#, like this:
void SaveOnDatabase()
{
QRDataBaseEntities DbContext = new QRDataBaseEntities();
Photo Item = new Photo();
Item.Name = Image1;
Item.Photo=b;
DbContext.Photos.Add(Item);
DbContext.SaveChanges();
}

Embedding SSRS 2016 reports into another webpage without iFrame?

Reporting-services 2016 (currently only available as a technical preview) comes with big-upgrades including HTML5 rendering and compliance. See: https://msdn.microsoft.com/en-us/library/ms170438.aspx
My desire is to embed SSRS 2016 reports into another webpage using native mode (no Sharepoint or aspx, just pure HTML5).
The traditional fashion to do this is to use an iFrame.
This is an half-way okay method as it's possible to remove the toolbar, hide parameters etc but still you end up losing a lot of control over the document. This is a cross-site implementation from a different domain so I can't manipulate the contained iFrame document as I please.
Does there exist an official way to embed the report element 'natively'?
I could envision a URL parameter option like rs:Format=REPORTDIV which serves me a html element.
I also tried fetching the report as an image (rs:Format=IMAGE&rc:OutputFormat=PNG) but the resulting PNG has a huge white frame (even when setting background to transparent in Report Builder) around the report element which is a no-go.
This should work. It should work outside of the environment as well as it embeds the images from memory instead of fetching them from the database
// Create service instance
ReportExecutionServiceSoapClient rsExec = new ReportExecutionServiceSoapClient(binding, endpoint);
rsExec.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
rsExec.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
ReportingServices.Extension[] extentions = null;
ReportingServices.TrustedUserHeader trustedUserHeader = new ReportingServices.TrustedUserHeader();
rsExec.ListRenderingExtensions(trustedUserHeader, out extentions);
string reportPath = "/Untitled";
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
ReportingServices.ServerInfoHeader serverInfo = new ReportingServices.ServerInfoHeader();
string historyID = null;
rsExec.LoadReport(trustedUserHeader, reportPath, historyID, out serverInfo, out execInfo);
//Get execution ID
execHeader.ExecutionID = execInfo.ExecutionID;
string deviceInfo = null;
string extension;
string encoding;
string mimeType;
ReportingServices.Warning[] warnings = new ReportingServices.Warning[1];
warnings[0] = new ReportingServices.Warning();
string[] streamIDs = null;
string format = "HTML5";
Byte[] result;
rsExec.Render(execHeader, trustedUserHeader, format, deviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamIDs);
var report = Encoding.UTF8.GetString(result);
int streamIdCount = streamIDs.Length;
Byte[][] imageArray = new Byte[streamIdCount][];
String[] base64Images = new String[streamIdCount];
for (int i = 0; i <= streamIdCount - 1; i++)
{
Byte[] result2;
string streamId = streamIDs[i];
rsExec.RenderStream(execHeader, trustedUserHeader, format, streamId, deviceInfo, out result2, out encoding, out mimeType);
imageArray[i] = result2;
base64Images[i] = Convert.ToBase64String(result2);
string replace = string.Format("https://<reportserver>/ReportServer?%2FUntitled&rs%3ASessionID={0}&rs%3AFormat={1}&rs%3AImageID={2}", execInfo.ExecutionID, format, streamId);
string src = string.Format("data:{0};charset=utf-8;base64, {1}", mimeType, base64Images[i]);
report = report.Replace(replace, src);
}

Dynamic variables in ActionScript 3.0

so.... eval() out of the question, any idea to do this? I also don't know how to use "this" expression or set() in actionscript 3 ( i seem couldn't find any complete reference on it ), just say through php file a multiple variable (test1, test2, test3,...) sent by "echo", how the flash aplication recieved it? I'm trying not to use xml on mysql to php to flash aplication. Simply how to change a string to a variable ?
example
(in as3-actions frame panel)
function datagridfill(event:MouseEvent):void{
var varfill:URLVariables = new URLVariables();
varfill.tell = "do it";
var filler:URLRequest = new URLRequest();
filler.url = "http://127.0.0.1/flashdbas3/sendin.php";
filler.data = varfill;
var filling:URLLoader = new URLLoader();
filling.dataFormat = URLLoaderDataFormat.VARIABLES;
filling.load(filler);
filling.addEventListener(Event.COMPLETE, datain);
function datain(evt:Event){
var arraygrid:Array = new Array();
testing.text = evt.target.Name2 // worked
// just say i = 1
i=1;
arraygrid.push({Name:this["evt.target.Name"+i],
Test:this.["evt.target.Test"+i]}); // error
//or
arraygrid.push({Name:this["Name"+i],
Test:this.["Test"+i]}); // error too
// eval() noexistent, set() didn't worked on actions frame panel
//?????
}
};
I hope it's very clear.
You could use this[varName] if I understand your question right.
So if varName is a variable containing a string which should be a variables name, you could set and read that variable like this:
this[varName] = "someValue";
trace(this[varName]);
Update:
In your example, you could try: evt.target["Test"+i] instead of Test:this.["evt.target.Test"+i]
If you have a set of strings that you'd like to associate with values, the standard AS3 approach is to use an object as a hash table:
var o = {}
o["test1"] = 7
o["test2"] = "fish"
print(o["test1"])