The player can create a room with certain properties that once created I set them and for lobby so that I can then display them in the lobby.
Function to create room:
public void OnCreateRoomButtonClicked()
{
RoomOptions roomOptions = new RoomOptions();
roomOptions.IsOpen = true;
roomOptions.IsVisible = true;
string roomName;
string gameMap;
if (gameMode.Equals("CarMeeting"))
{
gameMap = carMeetingModeMaps[mapIndex].sceneName;
roomName = roomNameCarMeetingModeInputField.text;
roomOptions.MaxPlayers = 4;
}
else
{
gameMap = racingModeMaps[mapIndex].sceneName;
roomName = roomNameRacingModeInputField.text;
roomOptions.MaxPlayers = 2;
}
if (!CheckIfRoomAlreadyExists(roomName))
{
StartCoroutine(EShowWarning());
}
else
{
roomOptions.CustomRoomProperties = new Hashtable();
roomOptions.CustomRoomProperties.Add("GameMap", gameMap);
roomOptions.CustomRoomProperties.Add("GameMode", gameMode);
roomOptions.CustomRoomProperties.Add("RaceMode", raceMode);
roomOptions.CustomRoomProperties.Add("InRace", false);
string[] customLobbyProperties = new string[4];
customLobbyProperties[0] = "GameMap";
customLobbyProperties[1] = "GameMode";
customLobbyProperties[2] = "RaceMode";
customLobbyProperties[3] = "InRace";
roomOptions.CustomRoomPropertiesForLobby = customLobbyProperties;
PhotonNetwork.CreateRoom(roomName, roomOptions, null, null);
}
}
Function display rooms in lobby:
public override void OnRoomListUpdate(List<RoomInfo> roomInfo)
{
Debug.Log("Rooms found " + roomInfo.Count);
bool roomFound = false;
foreach (RoomInfo room in roomInfo)
{
if (room.RemovedFromList)
{
int index = roomUIs.FindIndex(x => x.roomNameString.Equals(room.Name));
if (index != -1)
{
Destroy(roomUIs[index].gameObject);
roomUIs.RemoveAt(index);
}
}
else
{
CMRoomUI cacheRoomUI = roomUIs.Find(x => x.roomNameString.Equals(room.Name));
if (cacheRoomUI != null)
{
if (room.CustomProperties["GameMode"].ToString().Equals("CarMeeting"))
cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString());
else
cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString()
, room.CustomProperties["RacingMode"].ToString());
}
else
{
if (room.IsOpen)
{
CMRoomUI roomUI = Instantiate(roomUIPrefab.gameObject, roomUIParent).GetComponent<CMRoomUI>();
roomUIs.Add(roomUI);
if (room.CustomProperties["GameMode"].ToString().Equals("CarMeeting"))
roomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString());
else
cacheRoomUI.Check(room.Name, (room.PlayerCount + "/" + room.MaxPlayers).ToString(), room.CustomProperties["GameMap"].ToString(), room.CustomProperties["GameMode"].ToString()
, room.CustomProperties["RaceMode"].ToString());
}
}
}
}
if (roomUIs.Count > 0) roomFound = true;
noRoomTextObj.SetActive(!roomFound);
}
After I create a room if another player connects to the looby, I display the cameras visible with those properties, but the property "RaceMode" does not exist.
Related
I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.
This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...
I am working in ASP.Net to download the Image and I use the following code:
Code:
Main Method:
protected void btndownload_Click(object sender, EventArgs e)
{
FlyerBean objFlyerBean = SaveFlyer();
if (objFlyerBean == null)
return;
BindData(objFlyerBean);
string downLoadUrl = CommonUtil.GetBaseUrl() + "Preview/flyerview.aspx?FID=" + objFlyerBean.Id + "&Token=" + objFlyerBean.UserId + "&Size=" +
objFlyerBean.PreviewSize;
int previewWidth = -1;
int previwHeight = -1;
switch (objFlyerBean.PreviewSize)
{
case "8-5X11":
previewWidth = 885;
previwHeight = 980;
break;
case "5X7":
previewWidth = 524;
previwHeight = 814;
break;
case "4X6":
previewWidth = 428;
previwHeight = 696;
break;
}
Thread th = new Thread(delegate()
{
byte[] imgbyte = objScrenShotHelper.GenerateScreenshot(downLoadUrl, previewWidth, previwHeight);
Response.ContentType = "image/png";
Response.AppendHeader("content-disposition", "attachment; filename=" + DateTime.Now.Ticks + ".png");
Response.BinaryWrite(imgbyte);
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
Inner Methods:
private FlyerBean SaveFlyer()
{
FlyerBean objFlyerBean = new FlyerBean();
objFlyerBean.Id = string.IsNullOrEmpty(hfFlyerId.Value) ? 0 : Convert.ToInt64(hfFlyerId.Value);
objFlyerBean.Header = flyerHeader.Text.Trim();
objFlyerBean.Caption = flyerCaption.Text.Trim();
objFlyerBean.ChannelId = string.IsNullOrEmpty(hfSelectedChannelId.Value) ? 0 : Convert.ToInt32(hfSelectedChannelId.Value);
objFlyerBean.ChannelColor = hfchannelColor.Value;
objFlyerBean.FlyerImageSize = hfFlyerSize.Value;
objFlyerBean.FlyerLogoImageSize = hfFlyerLogoSize.Value;
if (!string.IsNullOrEmpty(hfImgePath.Value))
{
objFlyerBean.ImagePath = hfImgePath.Value;
objFlyerBean.ImageName = hfImageName.Value;
}
if (!string.IsNullOrEmpty(hflogoPath.Value))
{
objFlyerBean.BusinessLogo = hflogoPath.Value;
objFlyerBean.LogoName = hflogoName.Value;
}
objFlyerBean.BusinessName = flyerBusinessName.Text.Trim();
objFlyerBean.BackGroundColor = hfbgcolor.Value;
objFlyerBean.PreviewSize = hfViewSize.Value;
objFlyerBean.FieldsOrder = hfFieldOrder.Value;
objFlyerBean.UserId = new Guid(Session["user_id"].ToString());
FlyerBean Result = objFlyerHelper.SaveFlyer(objFlyerBean);
hfFlyerId.Value = "0";
if (Result == null)
return Result;
if (Result.Id > 0)
{
hfFlyerId.Value = Result.Id.ToString();
ViewState["flyerId"] = hfFlyerId.Value;
}
return Result;
}
private void BindData(FlyerBean objFlyerBean)
{
if (objFlyerBean != null)
{
SetBreadCrumb(true);
hfFlyerId.Value = objFlyerBean.Id.ToString();
hfHeader.Value = objFlyerBean.Header;
hfCaption.Value = objFlyerBean.Caption;
hfImgePath.Value = objFlyerBean.ImagePath;
hfImageName.Value = objFlyerBean.ImageName;
hfSelectedChannelId.Value = objFlyerBean.ChannelId.ToString();
hfchannelColor.Value = objFlyerBean.ChannelColor;
hfFlyerSize.Value = objFlyerBean.FlyerImageSize;
hfFlyerLogoSize.Value = objFlyerBean.FlyerLogoImageSize;
hflogoPath.Value = objFlyerBean.BusinessLogo;
hflogoName.Value = objFlyerBean.LogoName;
hfBusinessName.Value = objFlyerBean.BusinessName;
hfbgcolor.Value = objFlyerBean.BackGroundColor;
perviewImg.ImageUrl = objFlyerBean.ImagePath;
previewLogo.ImageUrl = objFlyerBean.BusinessLogo;
hfViewSize.Value = objFlyerBean.PreviewSize;
string orderval = "";
foreach (FlyerElementOrderBean objorder in objFlyerBean.ElementOrderList)
{
if (string.IsNullOrEmpty(orderval))
{
orderval = orderval + (objorder.ElementOrder - 1);
}
else
{
orderval = orderval + "," + (objorder.ElementOrder - 1);
}
}
hfFieldOrder.Value = orderval;
}
else
{
SetBreadCrumb(false);
hfFlyerId.Value = "0";
hfHeader.Value = "Sign up for Special Offers";
hfCaption.Value = "and receive a FREE soda with purchase!";
hfSelectedChannelId.Value = "-2";
hfchannelColor.Value = "#f68700";
hfbgcolor.Value = "#ffffff";
hfFlyerSize.Value = "m";
hfFlyerLogoSize.Value = "m";
hfImgePath.Value = CommonUtil.GetBaseUrl() + "images/PrevieImgDefault.png";
hflogoPath.Value = CommonUtil.GetBaseUrl() + "images/PreviewLogo.png";
hfImageName.Value = "PrevieImgDefault.png";
hflogoName.Value = "PreviewLogo.png";
hfBusinessName.Value = "Pizza by Joe";
hfViewSize.Value = "8-5X11";
hfFieldOrder.Value = "0,1,2,3";
}
}
But the issue is that while doing the same the values for all the hidden values that I used on the page have been lost. Can anyone tell me the problem behind this or any alternative that I can use. Thanks in advance.
I am working on Windows Phone 8 project. In my project there are 10 Events with 10 EventHandlers ReverseGeocodeQuery_QueryCompleted (1 to 10). When first EventHandler is completed it turn on second event.
What should I implement to manage those Events without so much code.
code
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(0);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_1;
myReverseGeocodeQuery.QueryAsync();
private void ReverseGeocodeQuery_QueryCompleted_1(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Pierwszy");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
}
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(1);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_2;
myReverseGeocodeQuery.QueryAsync();
}
}
private void ReverseGeocodeQuery_QueryCompleted_2(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Drugi");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(2);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_3;
myReverseGeocodeQuery.QueryAsync();
}
}
}
Example Solution 1
public class DataContainer
{
public string Description { get; set; }
public GeoCoordinate Coordinate { get; set; }
//public List<GeoCoordinate> mySimulationCoordinates { get; set; }
public String EnterSimulation() {
StringBuilder strRet = new StringBuilder();
List<GeoCoordinate> mySimulationCoordinates = new List<GeoCoordinate>();
mySimulationCoordinates.Add(new GeoCoordinate(51.760752, 19.458216));
mySimulationCoordinates.Add(new GeoCoordinate(51.760757, 19.458356));
mySimulationCoordinates.Add(new GeoCoordinate(51.760738, 19.458442));
mySimulationCoordinates.Add(new GeoCoordinate(51.7607, 19.458501));
mySimulationCoordinates.Add(new GeoCoordinate(51.760662, 19.458533));
var descriptions = new[] { "Pierwszy", "Drugi", "Trzeci", "Czwarty", "PiÄ…ty" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
int k = zipped.Count();
foreach (var item in zipped)
{
var currentItem = item;
using (var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = item.Coordinate;
geocodeQuery.QueryCompleted += (sender, args) =>
{
if (args.Error == null)
{
if (args.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
//label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("House Number" + address.HouseNumber);
str.AppendLine("Street " + address.Street);
strRet.AppendLine("->");
strRet.Append(str);
waitHandle.Set();
}
}
};
geocodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
return strRet.ToString();
}
It stuck on 1st item. Is inside and wait ... wait ... can't pass to next element.
Umm... Let's see, shouldn't that be easier?
Warning: untested
public class DataContainer
{
public string Description {get;set;}
public GeoCoordinate Coordinate {get;set;}
}
var descriptions = new[] {"Pierwszy" , "Drugi" , "Trzeci" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
foreach(var item in zipped)
{
var currentItem = item;
using(var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = currentItem.Coordinates;
geocodeQuery.QueryCompleted += (sender, args) => {
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
waitHandle.Set();
}
}
};
geoCodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
That should guarantee you that one event is handled after another in order.
How to make meeting (in calendar) in outlook 2007 using C# ?
thank's in advance
This code sample from MSDN should get you started:
private void SetRecipientTypeForAppt()
{
Outlook.AppointmentItem appt =
Application.CreateItem(
Outlook.OlItemType.olAppointmentItem)
as Outlook.AppointmentItem;
appt.Subject = "Customer Review";
appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
appt.Location = "36/2021";
appt.Start = DateTime.Parse("10/20/2006 10:00 AM");
appt.End = DateTime.Parse("10/20/2006 11:00 AM");
Outlook.Recipient recipRequired =
appt.Recipients.Add("Ryan Gregg");
recipRequired.Type =
(int)Outlook.OlMeetingRecipientType.olRequired;
Outlook.Recipient recipOptional =
appt.Recipients.Add("Peter Allenspach");
recipOptional.Type =
(int)Outlook.OlMeetingRecipientType.olOptional;
Outlook.Recipient recipConf =
appt.Recipients.Add("Conf Room 36/2021 (14) AV");
recipConf.Type =
(int)Outlook.OlMeetingRecipientType.olResource;
appt.Recipients.ResolveAll();
appt.Display(false);
}
MSDN
Create object of outlook app using:
private Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
and replace Application.CreateItem in code provided by Kyle Rozendo, with outlookApp.
Hope this will help.
This is probably a bit of an overkill but, here is a method that handles Adding, Updating, Deleting events. It also uses almost every calendar event function possible (recurrence by various types, attendees, responses etc.). If you're interested, let me know, I can explain more. It should work off the bat, but I could have missed something, typing this really fast
////BEGIN OUTLOOK DECLARATIONS
public static dynamic objOutlook = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application"));
public static int appointmentItem = 1;
public static int mailItem = 0;
public static int inboxItem = 6;
public static dynamic mapiNamespace = objOutlook.GetNamespace("MAPI");
public static dynamic inboxFolder = mapiNamespace.GetDefaultFolder(inboxItem);
public static dynamic mailObject = objOutlook.CreateItem(mailItem);
public static dynamic appointmentObject = objOutlook.CreateItem(appointmentItem);
public static string defaultEmail = mapiNamespace.DefaultStore.DisplayName; //mapiNamespace.CurrentUser.DefaultStore.DisplayName;
////END OUTLOOK DECLARATIONS
public static string CreateAppointmentOutlookDirect(char StatusType, int ID, string EventID, string EventIDRef, string Subject, string Description, string Location, DateTime EventStart, DateTime EventEnd, string TimeZone, int Duration,
string Recepients, bool isAllDayEvent, bool hasReminder, string ReminderType, int ReminderMinutes, bool isRecurring, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd,
DateTime CreatedDate, DateTime ModifiedDate)
{
RefreshOutlookConstants();
//ITEM TYPES
var olMailItem = 0;
var olAppointmentItem = 1;
//
//FOLDER TYPES
var olFolderCalendar = 9;
//
int RecurrenceMask = 0;
var objAppointment = objOutlook.CreateItem(olAppointmentItem);
var objMail = objOutlook.CreateItem(olMailItem);
var OlNamspace = objOutlook.GetNamespace("MAPI");
var AppointmentFolder = OlNamspace.GetDefaultFolder(olFolderCalendar);
var StoreID = AppointmentFolder.StoreID;
AppointmentFolder.Items.IncludeRecurrences = true;
string StatusTypeDesc = "";
string[] Attendees = Recepients.Split(';');
//UPDATE YEARLY RECURRENCE TYPE - BECAUSE THE NUMBER 4 DOES NOT EXIST ACCORDING TO MICROSOFT ( -_-)
if (RecurrenceType == 3)
{
RecurrenceType = 5;
}
//GET DAY OF WEEK
if (RecurrenceDesc.Trim().ToUpper() == "MONDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "TUESDAY")
{
RecurrenceMask = 4;
}
else if (RecurrenceDesc.Trim().ToUpper() == "WEDNESDAY")
{
RecurrenceMask = 8;
}
else if (RecurrenceDesc.Trim().ToUpper() == "THURSDAY")
{
RecurrenceMask = 16;
}
else if (RecurrenceDesc.Trim().ToUpper() == "FRIDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SATURDAY")
{
RecurrenceMask = 64;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SUNDAY")
{
RecurrenceMask = 1;
}
else
{
RecurrenceMask = 0;
}
//CHECK ALL DAY EVENT
if (isAllDayEvent)
{
EventStart = Convert.ToDateTime(EventStart.ToString("dd/MM/yyyy") + " 12:00 AM");
EventEnd = Convert.ToDateTime(EventEnd.AddDays(1).ToString("dd/MM/yyyy") + " 12:00 AM");
}
//--RESOLVE EVENT START - END - DURATION
GetEventDates(EventStart, EventEnd, Duration, out EventEnd, out Duration);
if (EventStart == null)
{
return EventID + "#FAIL";
}
//ADD - DELETE - UPDATE MEETING ACCORDINGLY
if (StatusType == 'D')
{
var aObject = OlNamspace.GetItemFromID(EventID, StoreID);
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
if (attendee.Trim() != "")
{
string NewAttendee = ExtractEmail(attendee);
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
aObject = null;
}
else
{
if (StatusType == 'U')
{
foreach (var aObject in AppointmentFolder.Items)
{
var EntryID = aObject.EntryID;
if (Convert.ToString(EntryID) == EventID.Trim())
{
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
}
}
}
objAppointment.MeetingStatus = 1;
objAppointment.Subject = Subject;
objAppointment.Body = Description;
objAppointment.Location = Location;
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
objAppointment.Recipients.Add(NewAttendee.Trim());
}
}
}
if (isAllDayEvent)
{
objAppointment.AllDayEvent = isAllDayEvent;
}
else
{
objAppointment.Start = EventStart;
objAppointment.End = EventEnd; //Optional if Event has Duration
objAppointment.Duration = Duration; //Optional if Event has Start and End
}
objAppointment.ReminderSet = hasReminder;
if (hasReminder)
{
objAppointment.ReminderMinutesBeforeStart = ReminderMinutes;
}
objAppointment.Importance = 2;
objAppointment.BusyStatus = 2;
if (isRecurring)
{
var pattern = objAppointment.GetRecurrencePattern();
pattern.RecurrenceType = RecurrenceType;
if (RecurrenceType == 1)
{
pattern.DayOfWeekMask = RecurrenceMask;
}
else if (RecurrenceType == 4)
{
pattern.MonthOfYear = RecurrenceMask;
}
if (DateTime.Compare(RecurrenceStart, DateTime.Now) > 1)
{
pattern.PatternStartDate = DateTime.Parse(RecurrenceStart.ToString("dd/MM/yyyy"));
}
if (DateTime.Compare(RecurrenceEnd, DateTime.Now) > 1)
{
pattern.PatternEndDate = DateTime.Parse(RecurrenceEnd.ToString("dd/MM/yyyy"));
}
}
objAppointment.Save();
if (Recepients.Trim() != "")
{
objAppointment.Send();
}
EventID = objAppointment.EntryID;
}
objAppointment = null;
//objOutlook = null;
// CREATE--UPDATE--DELETE EVENT OR APPOINTMENTS
StatusTypeDesc = GetStatusType(StatusType).Trim();
if (StatusTypeDesc == "")
{
clsGlobalFuncs.WriteServiceLog(String.Format("Error Creating Outlook Event: Unknown Status Type [{0}]. Event was Treated as a new event and may contain errors", StatusType));
return EventID + "#FAIL";
}
clsGlobalFuncs.WriteServiceLog(String.Format("Outlook Event Succesfully {2}. [EventID: {0}] ][EventRef: {1}]", EventID, EventIDRef, StatusTypeDesc));
return EventID + "#PASS";
}
public static void SendEmail(string Recepients, string CC, string BCC, string Subject, string Body, string Attachment)
{
RefreshOutlookConstants();
string[] EmailArr = Recepients.Split(';');
foreach (string email in EmailArr)
{
if (email.IndexOf('#') == -1)
{
WriteServiceLog(String.Format("EMAIL ERROR: Invalid Email Address:- [{0}]. This email will be skipped", email));
Recepients = Recepients.Replace(email + ";", "");
Recepients = Recepients.Replace(email, "");
}
}
if (Recepients.Trim() == "")
{
WriteServiceLog(String.Format("Error Sending Email. No recpients were found in string [{0}]", Recepients));
return;
}
try
{
Recepients = StringClean(Recepients);
// SEND EMAIL WITH ATTACHMENT
mailObject.To = Recepients;
if (CC.Trim() != "") { mailObject.CC = CC; }
if (BCC.Trim() != "") { mailObject.BCC = BCC; }
mailObject.Subject = Subject;
mailObject.HTMLBody = Body;
mailObject.Importance = 2;
if (Attachment.Trim() != "")
{
string[] attachmentList = Attachment.Split(';');
foreach (string attachmentFile in attachmentList)
{
if (attachmentFile.Trim() != "")
{
mailObject.Attachments.Add(attachmentFile.Trim());
}
}
}
mailObject.Send();
//objEmail.Display(false);
WriteServiceLog(String.Format("Email Sent [{0}] TO [{1}]", Subject, Recepients));
}
catch (Exception ex)
{
WriteServiceLog("Error sending email");
WriteErrorLog(ex);
}
}
public static string GetStatusType(char StatusCode)
{
string returnValue = "";
if (StatusCode == 'A')
{
returnValue = "Created";
}
else if (StatusCode == 'U')
{
returnValue = "Updated";
}
else if (StatusCode == 'D')
{
returnValue = "Deleted";
}
return returnValue;
}
public static string GetRecurData(bool RecurFlag, string EventType, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd, DateTime EventStart)
{
string returnValue = String.Format("RRULE:FREQ=DAILY;UNTIL={0:yyyyMMdd};", EventStart);
if (RecurFlag == true)
{
returnValue = "";
if (RecurrenceType == 0)
{
returnValue = String.Format("{0}RRULE:FREQ=DAILY;", returnValue);
}
else if (RecurrenceType == 1)
{
returnValue = returnValue + "RRULE:FREQ=WEEKLY;";
}
else if (RecurrenceType == 2)
{
returnValue = returnValue + "RRULE:FREQ=MONTHLY;";
}
else
{
returnValue = returnValue + "RRULE:FREQ=YEARLY;";
}
if (RecurrenceEnd != null)
{
returnValue = String.Format("{0}UNTIL={1:yyyyMMdd}T{2:HHmmss}Z;", returnValue, RecurrenceEnd, RecurrenceEnd);
}
if (EventType == "GM")
{
if (RecurrenceType == 1)
{
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYDAY={1};", returnValue, RecurrenceDesc.Substring(0, 2).ToUpper());
}
}
if (RecurrenceType == 3)
{
int i = DateTime.ParseExact(RecurrenceDesc, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month;
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYMONTH={1};", returnValue, i);
}
}
}
}
return returnValue;
}
public static string GetReminderType(bool ReminderFlag, string EventType, string ReminderCode)
{
string returnValue = "NONE";
if (ReminderFlag == true)
{
if (ReminderCode.Trim() == "PROMPT")
{
if (EventType == "GM")
{
returnValue = "popup";
}
else if (EventType == "OC")
{
returnValue = "DISPLAY";
}
}
else
{
returnValue = "email";
if (EventType == "OC") { returnValue = returnValue.ToUpper(); }
}
}
return returnValue;
}
public static void GetEventDates(DateTime EventStart, DateTime EventEnd, int Duration, out DateTime EventEnd_Ret, out int Duration_Ret)
{
EventEnd_Ret = EventEnd;
Duration_Ret = 0;
if (!(EventStart == null))
{
if (((EventEnd == null) || (DateTime.Compare(EventEnd, EventStart) < 1)) && (Duration > 0))
{
EventEnd_Ret = EventStart.AddMinutes(Duration);
}
else if ((Duration_Ret <= 0) && ((EventEnd != null) && (DateTime.Compare(EventEnd, EventStart) >= 0)))
{
Duration_Ret = Convert.ToInt32((EventEnd - EventStart).TotalMinutes);
}
if ((Duration_Ret <= 0) || ((EventEnd_Ret == null) || (DateTime.Compare(EventEnd_Ret, EventStart) < 1)))
{
WriteServiceLog(String.Format("ERROR UPDATING EVENT - COULD NOT RESOLVE WHEN THE EVENT MUST END USING [END DATE: {0:dd/MM/yyyy HH:mm}] OR [DURATION: {1}] - PLEASE SPECIFY A VALID END DATE OR DURATION", EventEnd, Duration));
}
}
else
{
WriteServiceLog("ERROR UPDATING EVENT - START DATE NOT FOUND");
}
}
public static string StringClean(string StringValue)
{
StringValue = StringValue.Replace(':',' ');
StringValue = StringValue.Replace('[', ' ');
StringValue = StringValue.Replace(']', ' ');
StringValue = StringValue.Replace('\'', ' ');
StringValue = StringValue.Replace('<', ' ');
StringValue = StringValue.Replace('>', ' ');
return StringValue.Trim();
}
And to call it, use this
CreateAppointmentOutlookDirect
(
'A', //'A' = ADD, 'U' = UPDATE, 'D' = DELETE
0,
"EVENT SUBJECT",
"OUTLOOK",
"",
"WHAT IS IT ABOUT",
"EVENT DESCRIPTION",
"EVENT LOCATION",
DateTime.Now,
DateTime.Now.AddMinutes(60),
TimeZone.CurrentTimeZone.StandardName,
0,
"attendee1#email.com; attendee2#email.com",
false,
true,
"PROMPT",
30,
false,
0,
"",
DateTime.Now,
DateTime.Now,
false,
'A',
"APPOINTMENT TEST SYSTEM"
);