I don't see any pictures in my RSS - c#

I have problem. I programming Windows Phone 8.0 application and i don't see anything pictures in my app. Probably error is in regex, because in debug regImg don't have any matches
Class MainPage.xaml.cs
string strURL = "https://news.google.com/news? cf=all&ned=pl_pl&hl=pl&topic=b&output=rss"; // URL of RssFeeds.
and class ImageFromRssText.cs
public class ImageFromRssText : IValueConverter
{
// Get images from each SyndicationItem.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
List<ImageItem> listUri = GetHtmlImageUrlList(value.ToString());
return listUri;
}
/// <summary>
/// Get the URL of the all pictures from the HTML.
/// </summary>
/// <param name="sHtmlText">HTML code</param>
/// <returns>URL list of the all pictures</returns>
public static List<ImageItem> GetHtmlImageUrlList(string sHtmlText)
{
// The definition of a regular expression to match img tag.
Regex regImg = new Regex(#"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// The search for a matching string.
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
List<ImageItem> imgUrlList = new List<ImageItem>();
// Get a list of matches
foreach (Match match in matches)
{
imgUrlList.Add(new ImageItem("img" + i, match.Groups["imgUrl"].Value));
i++;
}
return imgUrlList;
}

Ok. I wrote a little bit in a different way in second project(yesterday I wrote a project of a new). Although the problem is the same, then it does not load picture. Function HasImage always return false(Although when picture exists) and variabe Image is null(rest of variables are OK)
public class FeedItemViewModel : System.ComponentModel.INotifyPropertyChanged
{
// Declaration - Title, Image, Lead, Url
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
// All from RSS (Image and lead)
private string _lead;
public string Lead
{
get
{
return _lead;
}
set
{
_lead = value;
// Load picture
try
{
if (TryParseImageUrl(_lead, out _imageUrl))
_imageUrl = _imageUrl.Replace("//", "http://");
}
catch { }
OnPropertyChanged("Lead");
}
}
private string _imageUrl;
public Uri Image
{
get
{
if (HasImage)
return new Uri(_imageUrl, UriKind.RelativeOrAbsolute);
return null;
}
}
// Check if picture exists
public bool HasImage
{
get
{
return (!string.IsNullOrEmpty(_imageUrl) && Uri.IsWellFormedUriString(_imageUrl, UriKind.RelativeOrAbsolute));
}
}
// Download url news
private string _url;
public string Url
{
get
{
return _url;
}
set
{
_url = value;
OnPropertyChanged("Url");
}
}
public void OnOpenUrl()
{
var wb = new Microsoft.Phone.Tasks.WebBrowserTask();
wb.Uri = new Uri(_url);
wb.Show();
}
// 3 method parse image
private static bool TryParseImageUrl(string description, out string result)
{
string str = ParseAnyImageInTheDescription(description);
result = str;
return (!string.IsNullOrEmpty(str) && Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute));
}
private static string ParseAnyImageInTheDescription(string item)
{
if (item == null) { return null; }
return ParseImageUrlFromHtml(item);
}
private static string ParseImageUrlFromHtml(string html)
{
Match match = new Regex("src=(?:\\\"|\\')?(?<imgSrc>[^>]*[^/].(?:jpg|png|jpeg))(?:\\\"|\\')?").Match(html);
if ((match.Success && (match.Groups.Count > 1)) && (match.Groups[1].Captures.Count > 0))
{
return match.Groups[1].Captures[0].Value;
}
return null;
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}

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!

Understanding the error "the name does not exists in the current context"

I am using C#. I get an error:
The name 'DateAndTime','DateInterval' 'FirstDayOfWeek','FirstWeekOfYear', does not exist in the current context
which I don't understand. I tried a lot of solutions on it but it is not working.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using Microsoft.VisualBasic;
using System.Windows.Forms;
namespace SoftwareLocker
{
// Activate Property
public class TrialMaker
{
#region -> Private Variables
private string _BaseString;
private string _Password;
private string _SoftName;
private string _RegFilePath;
private string _HideFilePath;
private int _DefDays;
private int _Runed;
private string _Text;
private string _Identifier;
#endregion
#region -> Constructor
/// <summary>
/// Make new TrialMaker class to make software trial
/// </summary>
/// <param name="SoftwareName">Name of software to make trial</param>
/// <param name="RegFilePath">File path to save password(enrypted)</param>
/// <param name="HideFilePath">file path for saving hidden information</param>
/// <param name="Text">A text for contacting to you</param>
/// <param name="TrialDays">Default period days</param>
/// <param name="TrialRunTimes">How many times user can run as trial</param>
/// <param name="Identifier">3 Digit string as your identifier to make password</param>
public TrialMaker(string SoftwareName,
string RegFilePath, string HideFilePath,
string Text, int TrialDays, int TrialRunTimes,
string Identifier)
{
_SoftName = SoftwareName;
_Identifier = Identifier;
SetDefaults();
_DefDays = TrialDays;
_Runed = TrialRunTimes;
_RegFilePath = RegFilePath;
_HideFilePath = HideFilePath;
_Text = Text;
}
private void SetDefaults()
{
SystemInfo.UseBaseBoardManufacturer = false;
SystemInfo.UseBaseBoardProduct = true;
SystemInfo.UseBiosManufacturer = false;
SystemInfo.UseBiosVersion = true;
SystemInfo.UseDiskDriveSignature = true;
SystemInfo.UsePhysicalMediaSerialNumber = false;
SystemInfo.UseProcessorID = true;
SystemInfo.UseVideoControllerCaption = false;
SystemInfo.UseWindowsSerialNumber = false;
MakeBaseString();
MakePassword();
}
#endregion
// Make base string (Computer ID)
private void MakeBaseString()
{
_BaseString = Encryption.Boring(Encryption.InverseByBase(SystemInfo.GetSystemInfo(_SoftName), 10));
}
private void MakePassword()
{
_Password = Encryption.MakePassword(_BaseString, _Identifier);
}
/// <summary>
/// Show registering dialog to user
/// </summary>
/// <returns>Type of running</returns>
public RunTypes ShowDialog()
{
// check if registered before
if (CheckRegister() == true)
return RunTypes.Full;
frmDialog PassDialog = new frmDialog(_BaseString, _Password, DaysToEnd(), _Runed, _Text);
MakeHideFile();
DialogResult DR = PassDialog.ShowDialog();
if (DR == System.Windows.Forms.DialogResult.OK)
{
MakeRegFile();
return RunTypes.Full;
}
else if (DR == DialogResult.Retry)
return RunTypes.Trial;
else
return RunTypes.Expired;
}
// save password to Registration file for next time usage
private void MakeRegFile()
{
FileReadWrite.WriteFile(_RegFilePath, _Password);
}
// Control Registeration file for password
// if password saved correctly return true else false
private bool CheckRegister()
{
string Password = FileReadWrite.ReadFile(_RegFilePath);
if (_Password == Password)
return true;
else
return false;
}
// from hidden file
// indicate how many days can user use program
// if the file does not exists, make it
private int DaysToEnd()
{
FileInfo hf = new FileInfo(_HideFilePath);
if (hf.Exists == false)
{
MakeHideFile();
return _DefDays;
}
return CheckHideFile();
}
// store hidden information to hidden file
// Date,DaysToEnd,HowManyTimesRuned,BaseString(ComputerID)
private void MakeHideFile()
{
string HideInfo;
HideInfo = DateTime.Now.Ticks + ";";
HideInfo += _DefDays + ";" + _Runed + ";" + _BaseString;
FileReadWrite.WriteFile(_HideFilePath, HideInfo);
}
// Get Data from hidden file if exists
private int CheckHideFile()
{
string[] HideInfo;
HideInfo = FileReadWrite.ReadFile(_HideFilePath).Split(';');
long DiffDays;
int DaysToEnd;
if (_BaseString == HideInfo[3])
{
DaysToEnd = Convert.ToInt32(HideInfo[1]);
if (DaysToEnd <= 0)
{
_Runed = 0;
_DefDays = 0;
return 0;
}
DateTime dt = new DateTime(Convert.ToInt64(HideInfo[0]));
DiffDays = DateAndTime.DateDiff(DateInterval.Day,
dt.Date, DateTime.Now.Date,
FirstDayOfWeek.Saturday,
FirstWeekOfYear.FirstFullWeek);
DaysToEnd = Convert.ToInt32(HideInfo[1]);
_Runed = Convert.ToInt32(HideInfo[2]);
_Runed -= 1;
DiffDays = Math.Abs(DiffDays);
_DefDays = DaysToEnd - Convert.ToInt32(DiffDays);
}
return _DefDays;
}
public enum RunTypes
{
Trial = 0,
Full,
Expired,
UnKnown
}
#region -> Properties
/// <summary>
/// Indicate File path for storing password
/// </summary>
public string RegFilePath
{
get
{
return _RegFilePath;
}
set
{
_RegFilePath = value;
}
}
/// <summary>
/// Indicate file path for storing hidden information
/// </summary>
public string HideFilePath
{
get
{
return _HideFilePath;
}
set
{
_HideFilePath = value;
}
}
/// <summary>
/// Get default number of days for trial period
/// </summary>
public int TrialPeriodDays
{
get
{
return _DefDays;
}
}
/// <summary>
/// Get or Set TripleDES key for encrypting files to save
/// </summary>
public byte[] TripleDESKey
{
get
{
return FileReadWrite.key;
}
set
{
FileReadWrite.key = value;
}
}
#endregion
#region -> Usage Properties
public bool UseProcessorID
{
get
{
return SystemInfo.UseProcessorID;
}
set
{
SystemInfo.UseProcessorID = value;
}
}
public bool UseBaseBoardProduct
{
get
{
return SystemInfo.UseBaseBoardProduct;
}
set
{
SystemInfo.UseBaseBoardProduct = value;
}
}
public bool UseBaseBoardManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseDiskDriveSignature
{
get
{
return SystemInfo.UseDiskDriveSignature;
}
set
{
SystemInfo.UseDiskDriveSignature = value;
}
}
public bool UseVideoControllerCaption
{
get
{
return SystemInfo.UseVideoControllerCaption;
}
set
{
SystemInfo.UseVideoControllerCaption = value;
}
}
public bool UsePhysicalMediaSerialNumber
{
get
{
return SystemInfo.UsePhysicalMediaSerialNumber;
}
set
{
SystemInfo.UsePhysicalMediaSerialNumber = value;
}
}
public bool UseBiosVersion
{
get
{
return SystemInfo.UseBiosVersion;
}
set
{
SystemInfo.UseBiosVersion = value;
}
}
public bool UseBiosManufacturer
{
get
{
return SystemInfo.UseBiosManufacturer;
}
set
{
SystemInfo.UseBiosManufacturer = value;
}
}
public bool UseWindowsSerialNumber
{
get
{
return SystemInfo.UseWindowsSerialNumber;
}
set
{
SystemInfo.UseWindowsSerialNumber = value;
}
}
#endregion
}
}
that problem will work on Viaual basic 2005 it is not working in vb2015 if, we do so in 2015 some libraries are missing that pblm raises

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);
}
}
}

itunes listening to

within windows live messenger, it is possible to share the song you are currently listening to. what would i need to do to get this working within c# like libarys etc cannot find the correct documentation on google.
You'll need to use the iTunes SDK to interact with iTunes from .NET. So there's your Google search term. :)
Here's a start:
http://blogs.msdn.com/b/noahc/archive/2006/07/06/automating-itunes-with-c-in-net.aspx
http://blogs.msdn.com/b/dancre/archive/2004/05/08/128645.aspx
Here is a script for LinqPad in C# which does as requested. (see LinqPad.com)
Bonus! Artwork view.
It looks like this:
<Query Kind="Program">
<Namespace>iTunesLib</Namespace>
<Namespace>System.Security.Cryptography</Namespace>
</Query>
void Main()
{
var track = new iTunesApp().CurrentTrack;
if (track == null)
"nothing playing".Dump();
else
new Viewer(track,true).Dump();
}
public class Viewer
{
const string PREFIX = "itlps-";
private IITFileOrCDTrack store;
private bool materialize;
public string album { get { return store.Album; } }
public string band { get { return store.Artist; } }
public string song { get { return store.Name; } }
public string desc { get { return store.Description; } }
public int? artCnt { get {
if (store.Artwork == null) return null;
else return store.Artwork.Count; }
}
public IEnumerable<ImageViewer> art { get {
if (materialize)
{
foreach(var artT in store.Artwork)
{
var art = artT as IITArtwork;
string ext = ".tmp";
switch(art.Format)
{
case ITArtworkFormat.ITArtworkFormatBMP:
ext = ".BMP";
break;
case ITArtworkFormat.ITArtworkFormatJPEG:
ext = ".JPG";
break;
case ITArtworkFormat.ITArtworkFormatPNG:
ext = ".PNG";
break;
}
string path = Path.Combine(Path.GetTempPath(),PREFIX+Path.GetRandomFileName()+ext);
art.SaveArtworkToFile(path);
yield return new ImageViewer(path);
}
}
yield break; }
}
public Viewer(IITFileOrCDTrack t,bool materializeArt = false)
{
store = t;
materialize = materializeArt;
}
public Viewer(IITTrack t,bool materializeArt = false)
{
store = t as IITFileOrCDTrack;
materialize = materializeArt;
}
}
public class ImageViewer
{
public string hash { get { return _hash.Value; } }
static private string _path { get; set; }
public object image { get { return _image.Value; } }
static private SHA1Managed sha = new SHA1Managed();
private Lazy<object> _image = new Lazy<object>(() => {return Util.Image(_path);});
private Lazy<string> _hash = new Lazy<string>(() =>
{
string hash = string.Empty;
using (FileStream stream = File.OpenRead(_path))
{
byte [] checksum = sha.ComputeHash(stream);
hash = BitConverter.ToString(checksum).Replace("-", string.Empty);
}
return hash;
});
public ImageViewer(string path)
{
_path = path;
}
}
last i checked this functionality is included out of the box all you need is to have itunes and windows live messenger installed and activate "what im listening to" and it shows this in your messenger status. if you are looking to create a bot that messages this out to a contact that is a different story tho that you will need to write a script for

Categories