Return newtonsoft json object from WebMethod - c#

I want to return a JSON object from a c# webmethod if i use return i have an error "recussive reference found". So i decided to use newtonsoft serialize but the returned object are in double quote. {d:"my json"} and didn't work.
I try to use this code :
[WebMethod(EnableSession = true)]
public static void RecordList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
string error;
var result = DataTools.Data("select id_individu,nom_indiv from individu limit 10",
WebConfigurationManager.ConnectionStrings["TabloidConnection"].ConnectionString,
out error);
var rep = System.Web.HttpContext.Current.Response;
rep.Clear();
rep.ClearContent();
rep.BufferOutput = true;
rep.ContentType = "application/json; charset=UTF-8";
//rep.Write("ab");
rep.Write("{d:");
rep.Write(JsonConvert.SerializeObject(new jTableResponse(result), Formatting.None));
rep.Write("}");
rep.Flush();
//rep.SuppressContent = true;
rep.End();
//ct.ApplicationInstance.CompleteRequest();
}
public class jTableResponse
{
private int totalRecordCount=0;
private DataTable records;
private string result = "OK";
public string Result
{
get { return result; }
set { result = value; }
}
public int TotalRecordCount
{
get { return totalRecordCount; }
set { totalRecordCount = value; }
}
public DataTable Records
{
get { return records; }
set { records = value; }
}
public jTableResponse(DataTable r)
{
Records = r;
totalRecordCount = r.Rows.Count;
}
}
But i have character added behind and after my json like this (using fiddler)
1d0
{d:{"Result":"OK","TotalRecordCount":10,"Records":[{"id_individu":1,"nom_indiv":"..."},{"id_individu":2,"nom_indiv":"RIVET"},{"id_individu":3,"nom_indiv":"COHEN"},{"id_individu":4,"nom_indiv":"VILLEROUGE"},{"id_individu":5,"nom_indiv":"CAILLARD"},{"id_individu":6,"nom_indiv":"DE CHEVRON VILLETTE"},{"id_individu":7,"nom_indiv":"ROYO"},{"id_individu":8,"nom_indiv":"ROQUES"},{"id_individu":9,"nom_indiv":"GUILLOT"},{"id_individu":10,"nom_indiv":"DORNE-CORRAZE"}]}}
0
Thanks for your response

When i change this
rep.Write("{d:");
rep.Write(JsonConvert.SerializeObject(new jTableResponse(result), Formatting.None));
rep.Write("}");
by this
rep.Write(JsonConvert.SerializeObject(new jTableResponse(result), Formatting.None));
it work fine thanks.

Related

.NET Web API is getting null XML from Post

So I am very new to the whole .NET world, so I could very well have some terminology off. I was asked to help with making some changes to this code because I've helped with some other dev work (entirely different systems). Anyway, I can't even get it to run on my test system to begin the actual work - yet they are already using this code in production so I'm assuming it's just an inconsistency in my setup. Either way though I'm trying to drill down into the code to both learn it better and hopefully understand what could be going wrong with my system.
So this API does not have a front end, all of the testing is being done from Postman. It's supposed to post a request with an XML body to a function that then reads the XML and retrieves data. For whatever reason the request that is passed in always comes up NULL, though I think I verified that Postman is submitting the data because I tried the third answer here: Getting raw POST data from Web API method and I do see the full body of the request then.
Here is the method it is posting to:
[Route("summary")]
[ResponseType(typeof(SummarySearchResponseType))]
public IHttpActionResult PostSummary([FromBody] SummarySearchRequestType req)
{
try
{
var response = _searchService.GetSummary(req);
if (response == null)
{
return BadRequest();
}
return Ok(response);
}
catch
{
return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}
}
Here is that SearchService function:
public SummarySearchResponseType GetSummary(SummarySearchRequestType request)
{
Serilog.Log.Information("GetSummary request = {0}", request);
// Validate required fields in request
if (request == null)
{
Serilog.Log.Logger.Warning("One or more required search fields are missing");
return null;
}
if (string.IsNullOrEmpty(request.ClientNumber))
{
Serilog.Log.Logger.Warning("Missing required search field 'ClientNumber'");
return null;
}
if (request.LossDate == null)
{
Serilog.Log.Logger.Warning("Missing required search field 'LossDate'");
return null;
}
var response = new SummarySearchResponseType
{
RequestID = request.RequestID
};
try
{
using (IMultipleResults sprocResults = _dataContext.UspGetDetailedResponse(
request.ClientNumber,
request.PolicyNumber,
request.PolicySuffix,
request.ClientAccountNum,
request.LossDate.ToShortDateString(),
request.PolicyType,
request.LineCode,
request.AgencyCode,
request.Searchtype,
request.Lob,
request.InsuredSearch?.FirstName,
request.InsuredSearch?.LastName,
request.InsuredSearch?.FullName,
request.InsuredSearch?.DBAName,
request.InsuredSearch?.Address.Address1,
request.InsuredSearch?.Address.Address2,
request.InsuredSearch?.Address.City,
request.InsuredSearch?.Address.State,
request.InsuredSearch?.Address.PostalCode,
request.InsuredSearch?.Address.County,
request.InsuredSearch?.Address.Country,
request.InsuredSearch?.ClientAccountnumber,
request.InsuredSearch?.Email,
request.InsuredSearch?.Phone,
request.InsuredSearch?.Comment,
request.RiskUnitSearch?.RiskUnitID,
request.RiskUnitSearch?.RiskUnitName,
request.RiskUnitSearch?.LocationSearch?.BuildingID,
request.RiskUnitSearch?.LocationSearch?.Address?.Address1,
request.RiskUnitSearch?.LocationSearch?.Address?.Address2,
request.RiskUnitSearch?.LocationSearch?.Address?.City,
request.RiskUnitSearch?.LocationSearch?.Address?.State,
request.RiskUnitSearch?.LocationSearch?.Address?.PostalCode,
request.RiskUnitSearch?.LocationSearch?.Address?.County,
request.RiskUnitSearch?.LocationSearch?.Address?.Country,
request.RiskUnitSearch?.VehicleSearch.VIN,
request.RiskUnitSearch?.VehicleSearch.Year,
request.RiskUnitSearch?.VehicleSearch.Make))
{
// Policies
//
var result1 = sprocResults.GetResult<UspGetDetailedResponseResult1>();
var policies = _mapper.Map<IEnumerable<PolicyType>>(result1).ToArray();
// Insured
//
var result2 = sprocResults.GetResult<UspGetDetailedResponseResult2>();
var insured = _mapper.Map<IEnumerable<ParticipantType>>(result2).ToArray();
//Risk Unit
//
var result3 = sprocResults.GetResult<UspGetDetailedResponseResult3>();
var riskUnits = _mapper.Map<IEnumerable<RiskUnitType>>(result3).ToArray();
// Attach Participants and RiskUnits to Policies via PolicyNumber
//
policies.ToList().ForEach(p =>
{
p.Participants = insured.Where(i => i.PolicyNumber == p.PolicyNumber).ToArray();
p.RiskUnits = riskUnits.Where(i => i.PolicyNumber == p.PolicyNumber).ToArray();
});
response.Policies = policies;
response.PolicyCnt = policies.Length.ToString();
Serilog.Log.Information("GetSummary response = {0}", response);
return response;
}
}
catch (Exception ex)
{
Serilog.Log.Error(ex, $"{ex}", ex);
throw ex;
}
}
And here is the SummarySearchRequestType:
public partial class SummarySearchRequestType
{
public override string ToString()
{
XmlSerializer responseSerializer = new XmlSerializer(this.GetType());
using (StringWriter responseWriter = new StringWriter())
{
responseSerializer.Serialize(responseWriter, this);
var xmlResponse = responseWriter.ToString();
return xmlResponse;
}
}
}
And the rest of it:
public partial class SummarySearchRequestType {
private string requestIDField;
private string clientNumberField;
private string policyNumberField;
private string policySuffixField;
private string clientAccountNumField;
private System.DateTime lossDateField;
private bool lossDateFieldSpecified;
private string policyTypeField;
private string lineCodeField;
private InsuredSearchType insuredSearchField;
private RiskUnitSearchType riskUnitSearchField;
private string agencyCodeField;
private string searchtypeField;
private string lobField;
/// <remarks/>
public string RequestID {
get {
return this.requestIDField;
}
set {
this.requestIDField = value;
}
}
/// <remarks/>
public string ClientNumber {
get {
return this.clientNumberField;
}
set {
this.clientNumberField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicyNumber {
get {
return this.policyNumberField;
}
set {
this.policyNumberField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicySuffix {
get {
return this.policySuffixField;
}
set {
this.policySuffixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string ClientAccountNum {
get {
return this.clientAccountNumField;
}
set {
this.clientAccountNumField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
public System.DateTime LossDate {
get {
return this.lossDateField;
}
set {
this.lossDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool LossDateSpecified {
get {
return this.lossDateFieldSpecified;
}
set {
this.lossDateFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string PolicyType {
get {
return this.policyTypeField;
}
set {
this.policyTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string LineCode {
get {
return this.lineCodeField;
}
set {
this.lineCodeField = value;
}
}
/// <remarks/>
public InsuredSearchType InsuredSearch {
get {
return this.insuredSearchField;
}
set {
this.insuredSearchField = value;
}
}
/// <remarks/>
public RiskUnitSearchType RiskUnitSearch {
get {
return this.riskUnitSearchField;
}
set {
this.riskUnitSearchField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string AgencyCode {
get {
return this.agencyCodeField;
}
set {
this.agencyCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string Searchtype {
get {
return this.searchtypeField;
}
set {
this.searchtypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="http://sedgwickcms.com/claims/entities/Policy/v1310")]
public string Lob {
get {
return this.lobField;
}
set {
this.lobField = value;
}
}
}
And in Postman I'm sending a post to the server with this raw XML body:
<?xml version="1.0" encoding="utf-8" ?><SummarySearchRequest xmlns="***"> 
<RequestID>***</RequestID>  <ClientNumber>***</ClientNumber>  <LossDate>***</LossDate>  <PolicyNumber xmlns="***">***</PolicyNumber>
</SummarySearchRequest>
NOTE - I replaced specific data with ***.
Postman is hitting the server, and like I said I was able to verify based on that other post that actual data is getting to the server, but somewhere it is not setting the object properly (or something else). This is running on a VM of windows 11, through IIS Express in Visual Studio which automatically serves the https on port 44375 if that matters. I'd appreciate any insight into what could be the issue, if you need any more information please let me know - I do not understand .NET well yet. Thank you!

C# CurlSharp EasyGet - How to get string result

I'm using this code to make an EasyGet request.Does anyone know how to get a string result?
using CurlSharp;
public static void CurlSharpGet(string url, bool useHttp2 = true)
{
Curl.GlobalInit(CurlInitFlag.All);
try
{
if (useHttp2)
{
using (var easy = new CurlEasy())
{
easy.Url = url;
easy.WriteFunction = OnWriteData;
easy.HttpVersion = CurlHttpVersion.Http2_0;
easy.SslVerifyPeer = false;
easy.SslVerifyhost = false;
easy.Perform();
Console.WriteLine(easy.Perform());
}
}
else
{
using (var easy = new CurlEasy())
{
easy.Url = url;
easy.WriteFunction = OnWriteData;
easy.Perform();
Console.WriteLine(easy.Perform());
}
}
}
finally
{
Curl.GlobalCleanup();
}
}
public static Int32 OnWriteData(byte[] buf, Int32 size, Int32 nmemb, object data)
{
Console.Write(Encoding.UTF8.GetString(buf));
return size * nmemb;
}
Ideally i would like to have something that looks like this:
public static string CurlSharpGet(string url, bool useHttp2 = true)
{
//my fixed code here
}
The nature of what I'm doing cannot be accomplished using httpclient or webresponse. Would appreciate any advice on what I should do to get the above code to return a string result. Thanks

C# Class Properties 'tied' to a file? (See Perl::Tie)

In perl there's a rather simple method of tying a data structure to a file, whether it be a string, hash(dictionary in C#) or a simple array/list.
I've cobbled together my own half-assed solution in C# but I was wondering if there's a more inbuilt way to achieve this functionality?
Edit in response to comment below--The question, directly: Is there an inbuilt way to "tie" a class/dictionary to a file so any changes in either is reflected in the other? (Without doing as I've done below)
(Tieing a dictionary means that any changes in the dictionary are immediately reflected/updated in the file and declaring a tied var loads the object from disk if it already exists; see PerlTie )
My pseudo-tie'd class is below:
#region options
private float _Opacity;
public float Opacity {
get {
return Opacity;
}
set {
_Opacity = value;
this.Save();
}
}
private Font _Font;
public Font Font {
get {
return _Font;
}
set {
_Font = value;
this.Save();
}
}
private Color _FontColor;
public Color FontColor {
get {
return _FontColor;
}
set {
_FontColor = value;
this.Save();
}
}
private Color _BGColor;
public Color BGColor {
get {
return _BGColor;
}
set {
_BGColor = value;
this.Save();
}
}
private Point _Location;
public Point Location {
get {
return _Location;
}
set {
_Location = value;
this.Save();
}
}
private Size _Size;
public Size Size {
get {
return _Size;
}
set {
_Size = value;
this.Save();
}
}
private ushort _HistoryLines;
public ushort HistoryLines {
get {
return _HistoryLines;
}
set {
_HistoryLines = value;
this.Save();
}
}
private ChatType _ChatModes;
public ChatType ChatModes {
get {
return _ChatModes;
}
set {
_ChatModes = value;
this.Save();
}
}
private bool _Debugging;
public bool Debugging {
get {
return _Debugging;
}
set {
_Debugging = value;
this.Save();
}
}
#endregion options
private FontConverter FontConvert;
private FileInfo SettingsFile;
private MLogConf() {
}
public MLogConf(string stateFile) {
FontConvert = new FontConverter();
try {
if (!Directory.Exists(Path.GetDirectoryName(stateFile)))
Directory.CreateDirectory(Path.GetDirectoryName(stateFile));
if (!File.Exists(stateFile)) {
FileStream fs = File.Create(stateFile);
fs.Close();
}
SettingsFile = new FileInfo(stateFile);
if (SettingsFile.Length == 0) {
this.SetDefaultOptions();
} else {
if (!this.Load()) {
throw new FileLoadException("Couldn't load settings file");
}
}
} catch (Exception ex) {
Trace.Write($"Failed to create MLogConf({nameof(stateFile)}) {ex.Message + Environment.NewLine + ex.StackTrace}");
}
}
private bool Load() {
if (SettingsFile == null)
return false;
try {
byte[] data = File.ReadAllBytes(SettingsFile.FullName);
using (MemoryStream m = new MemoryStream(data)) {
using (BinaryReader reader = new BinaryReader(m)) {
_Opacity = reader.ReadSingle();
_Font = (Font)(FontConvert.ConvertFromString(Encoding.ASCII.GetString(Convert.FromBase64String(reader.ReadString()))));
_FontColor = Color.FromArgb(reader.ReadInt32());
_BGColor = Color.FromArgb(reader.ReadInt32());
_Location = new Point(reader.ReadInt32(), reader.ReadInt32());
_Size = new Size(reader.ReadInt32(), reader.ReadInt32());
_HistoryLines = reader.ReadUInt16();
_ChatModes = (ChatType)reader.ReadInt32();
_Debugging = reader.ReadBoolean();
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception reading binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool Save() {
try {
using (FileStream fs = new FileStream(SettingsFile.FullName, FileMode.Create)) {
using (BinaryWriter writer = new BinaryWriter(fs)) {
writer.Write(_Opacity);
writer.Write(Convert.ToBase64String(Encoding.ASCII.GetBytes((string)FontConvert.ConvertTo(Font, typeof(string)))));
writer.Write(_FontColor.ToArgb());
writer.Write(_BGColor.ToArgb());
writer.Write(_Location.X);
writer.Write(_Location.Y);
writer.Write(_Size.Width);
writer.Write(_Size.Height);
writer.Write(_HistoryLines);
writer.Write((int)_ChatModes);
writer.Write(_Debugging);
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception writing binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool SetDefaultOptions() {
this._BGColor = Color.Black;
this._ChatModes = ChatType.Alliance | ChatType.Emote | ChatType.FreeCompany | ChatType.Linkshell | ChatType.Party | ChatType.SayShoutYell | ChatType.Tell;
this._Opacity = 1f;
this._Font = new Font("Verdana", 50);
this._FontColor = Color.CornflowerBlue;
this._Location = new Point(100, 400);
this._Size = new Size(470, 150);
this._HistoryLines = 512;
this._Debugging = false;
return this.Save();
}
I suppose you are looking for an easy way to store class instances in files.
Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
The shortest solution I've found for C# here some time ago was Json.NET from Newtonsoft, available as NuGet package. It will do all the 'long class-properties-to-string code' for you and leave you with string ready to be written in file.
Official site can provide code examples: http://www.newtonsoft.com/json
Save to file:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
Read from file:
string json = #"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys

I am trying to access data in a C# packet I've created, however I keep getting null as a response. What am I doing wrong?

Okay, so I'm working with custom network code for pretty much the first time. I have a packet created to transfer some game information back and forth, however beyond the initial content if I try to access some of the commands, I get "null" - though on the server side, it's showing as properly populated.
I have a feeling that this has to do with the setup in receiving the data. The code for the packet follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum DataIdentifier
{
Message,
Command,
LogIn,
LogOut,
Null
}
public class Packet
{
private DataIdentifier dataIdentifier;
private string name;
private string player;
private string playerData;
private string message;
private string command;
private string x;
private string y;
private string z;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Player
{
get
{
return player;
}
set
{
player = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string Command
{
get
{
return command;
}
set
{
command = value;
}
}
public DataIdentifier DataIdentifier
{
get
{
return dataIdentifier;
}
set
{
dataIdentifier = value;
}
}
public string PlayerData
{
get
{
return playerData;
}
set
{
playerData = value;
}
}
public string X
{
get
{
return x;
}
set
{
x = value;
}
}
public string Y
{
get
{
return y;
}
set
{
y = value;
}
}
public string Z
{
get
{
return z;
}
set
{
z = value;
}
}
public Packet()
{
this.DataIdentifier = DataIdentifier.Null;
this.message = null;
this.name = null;
this.player = null;
this.playerData = null;
this.x = null;
this.y = null;
this.z = null;
this.command = null;
}
public Packet(byte[] dataStream)
{
// Read the data identifier from the beginning of the stream (4 bytes)
this.DataIdentifier = (DataIdentifier)BitConverter.ToInt32(dataStream, 0);
// Read the length of the name (4 bytes)
int nameLength = BitConverter.ToInt32(dataStream, 4);
// Read the length of the message (4 bytes)
int msgLength = BitConverter.ToInt32(dataStream, 8);
// Read the name field
if (nameLength > 0)
this.name = Encoding.UTF8.GetString(dataStream, 12, nameLength);
else
this.name = null;
// Read the message field
if (msgLength > 0)
this.message = Encoding.UTF8.GetString(dataStream, 12 + nameLength, msgLength);
else
this.message = null;
}
public byte[] GetDataStream()
{
List<byte> dataStream = new List<byte>();
// Add the dataIdentifier
dataStream.AddRange(BitConverter.GetBytes((int)this.DataIdentifier));
// Add the name length
if (this.name != null)
dataStream.AddRange(BitConverter.GetBytes(this.name.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the message length
if (this.message != null)
dataStream.AddRange(BitConverter.GetBytes(this.message.Length));
else
dataStream.AddRange(BitConverter.GetBytes(0));
// Add the name
if (this.name != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.name));
// Add the message
if (this.message != null)
dataStream.AddRange(Encoding.UTF8.GetBytes(this.message));
if (this.playerData != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.playerData));
}
if (this.command != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.command));
}
if (this.x != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.x));
}
if (this.y != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.y));
}
if (this.z != null)
{
dataStream.AddRange(Encoding.UTF8.GetBytes(this.z));
}
return dataStream.ToArray();
}
}
This is how the packet is recieved:
// Receive all data
this.clientSocket.EndReceive(AR);
// Initialise a packet object to store the received data
Packet receivedData = new Packet(this.dataStream);
// Evaulate command played
if (PacketDelegate != null)
{
PacketDelegate(receivedData);
}
// Reset data stream
this.dataStream = new byte[8142];
// Continue listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveCallback), null);
And this is the delegate function responsible for handling a packet:
public void RecievePacket(Packet Communication)
{
// Check and manipulate the contents of the packet here //
}
I have confirmed that I can get name, DataIdentifier, and Message, but it's the additional information I've added to the packet itself - player/data, command, x,y,z, I can't seem to get.
My thought is that the problem exists in establishing Packet(byte[] dataStream). However, I'm not quite sure how to calculate or add the additional variables to this. Can anyone give me some tips on how to do so?

Set default value for string prompt

The editor class has a method called GetString which prompts the user for a string value via AutoCAD's command prompt. I call it in this wrapper method:
public static string PromptUserForString(string message = "Enter a string: ", string defaultAnswer = "")
{
return _editor.GetString("\n" + message).StringResult;
}
The argument message becomes the message the user sees when prompted for a string. How do I set it up so that the value of default answer is automatically set to be the answer so that if the user hits enter right away that becomes the value like in the screen shot below
So 1 is automatically typed as an answer meaning the user can either hit enter for the value of 1 or change 1 to whatever non-default answer they want
I paste you some code as example for the different prompts :
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
namespace EditorUtilities
{
/// <summary>
/// Prompts with the active document ( MdiActiveDocument )
/// </summary>
public class EditorHelper : IEditorHelper
{
private readonly Editor _editor;
public EditorHelper(Document document)
{
_editor = document.Editor;
}
public PromptEntityResult PromptForObject(string promptMessage, Type allowedType, bool exactMatchOfAllowedType)
{
var polyOptions = new PromptEntityOptions(promptMessage);
polyOptions.SetRejectMessage("Entity is not of type " + allowedType);
polyOptions.AddAllowedClass(allowedType, exactMatchOfAllowedType);
var polyResult = _editor.GetEntity(polyOptions);
return polyResult;
}
public PromptPointResult PromptForPoint(string promptMessage, bool useDashedLine = false, bool useBasePoint = false, Point3d basePoint = new Point3d(),bool allowNone = true)
{
var pointOptions = new PromptPointOptions(promptMessage);
if (useBasePoint)
{
pointOptions.UseBasePoint = true;
pointOptions.BasePoint = basePoint;
pointOptions.AllowNone = allowNone;
}
if (useDashedLine)
{
pointOptions.UseDashedLine = true;
}
var pointResult = _editor.GetPoint(pointOptions);
return pointResult;
}
public PromptPointResult PromptForPoint(PromptPointOptions promptPointOptions)
{
return _editor.GetPoint(promptPointOptions);
}
public PromptDoubleResult PromptForDouble(string promptMessage, double defaultValue = 0.0)
{
var doubleOptions = new PromptDoubleOptions(promptMessage);
if (Math.Abs(defaultValue - 0.0) > Double.Epsilon)
{
doubleOptions.UseDefaultValue = true;
doubleOptions.DefaultValue = defaultValue;
}
var promptDoubleResult = _editor.GetDouble(doubleOptions);
return promptDoubleResult;
}
public PromptIntegerResult PromptForInteger(string promptMessage)
{
var promptIntResult = _editor.GetInteger(promptMessage);
return promptIntResult;
}
public PromptResult PromptForKeywordSelection(
string promptMessage, IEnumerable<string> keywords, bool allowNone, string defaultKeyword = "")
{
var promptKeywordOptions = new PromptKeywordOptions(promptMessage) { AllowNone = allowNone };
foreach (var keyword in keywords)
{
promptKeywordOptions.Keywords.Add(keyword);
}
if (defaultKeyword != "")
{
promptKeywordOptions.Keywords.Default = defaultKeyword;
}
var keywordResult = _editor.GetKeywords(promptKeywordOptions);
return keywordResult;
}
public Point3dCollection PromptForRectangle(out PromptStatus status, string promptMessage)
{
var resultRectanglePointCollection = new Point3dCollection();
var viewCornerPointResult = PromptForPoint(promptMessage);
var pointPromptStatus = viewCornerPointResult.Status;
if (viewCornerPointResult.Status == PromptStatus.OK)
{
var rectangleJig = new RectangleJig(viewCornerPointResult.Value);
var jigResult = _editor.Drag(rectangleJig);
if (jigResult.Status == PromptStatus.OK)
{
// remove duplicate point at the end of the rectangle
var polyline = rectangleJig.Polyline;
var viewPolylinePoints = GeometryUtility.GetPointsFromPolyline(polyline);
if (viewPolylinePoints.Count == 5)
{
viewPolylinePoints.RemoveAt(4); // dont know why but true, probably mirror point with the last point
}
}
pointPromptStatus = jigResult.Status;
}
status = pointPromptStatus;
return resultRectanglePointCollection;
}
public PromptSelectionResult PromptForSelection(string promptMessage = null, SelectionFilter filter = null)
{
var selectionOptions = new PromptSelectionOptions { MessageForAdding = promptMessage };
var selectionResult = String.IsNullOrEmpty(promptMessage) ? _editor.SelectAll(filter) : _editor.GetSelection(selectionOptions, filter);
return selectionResult;
}
public PromptSelectionResult PromptForSelection(PromptSelectionOptions promptSelectionOptions,SelectionFilter filter = null)
{
return _editor.GetSelection(promptSelectionOptions, filter);
}
public void WriteMessage(string message)
{
_editor.WriteMessage(message);
}
public void DrawVector(Point3d from, Point3d to, int color, bool drawHighlighted)
{
_editor.DrawVector(from, to, color, drawHighlighted);
}
}
}

Categories