I am using 2013 Excel and am testing a web application where i need to analyze a excel file using code so i found a code which i have modified according to ranorex namings. but am new to ranorex so getting few errors. this is the error am facing even after adding the reference.
No overload for method 'Open' takes 15 arguments (CS1501)
Please help me out
/
*
* Created by Ranorex
* User: ppatlolla
* Date: 26/08/2015
* Time: 10:57 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using WinForms = System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Testing;
namespace CCMWebReports
{
/// <summary>
/// Description of ReadExcelFile.
/// </summary>
[TestModule("7FA20A0A-9E9B-4FE2-9DC7-3FAE3AFA5E58", ModuleType.UserCode, 1)]
public class ReadExcelFile : ITestModule
{
/// <summary>
/// Constructs a new instance.
/// </summary>
public ReadExcelFile()
{
// Do not delete - a parameterless constructor is required!
}
/// <summary>
/// Performs the playback of actions in this module.
/// </summary>
/// <remarks>You should not call this method directly, instead pass the module
/// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method
/// that will in turn invoke this method.</remarks>
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
}
}
public partial class Form1 : Form
{
//public Form1()
// {
// InitializeComponent();
// }
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1010-AgentPerformancebyPeriod-2015081214195339.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
Report.Info(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Report.Info("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
I think you have too many arguments in your xlApp.Workbooks.Open function.
Remove the last 2 parameters after the last 'true' and it should compile successfully:
xlWorkBook = xlApp.Workbooks.Open("1010-AgentPerformancebyPeriod-2015081214195339.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true);
Related
My Team-recording bot code is running in azure Kubernetes service. The code is written in the .netframework language. The bot can join the team meeting and it is recording the meeting and saving the files in audio(wav) format to local in a .zip file. I want to process the video files to local in a .zip file. Right now we have AudioProcessor class to get the audio files:` public BotMediaStream(
ILocalMediaSession mediaSession,
string callId,
IGraphLogger logger,
IEventPublisher eventPublisher,
IAzureSettings settings
)
: base(logger)
{
ArgumentVerifier.ThrowOnNullArgument(mediaSession, nameof(mediaSession));
ArgumentVerifier.ThrowOnNullArgument(logger, nameof(logger));
ArgumentVerifier.ThrowOnNullArgument(settings, nameof(settings));
this.participants = new List<IParticipant>();
_eventPublisher = eventPublisher;
_callId = callId;
_mediaStream = new MediaStream(
settings,
logger,
mediaSession.MediaSessionId.ToString()
);
// Subscribe to the audio media.
this._audioSocket = mediaSession.AudioSocket;
if (this._audioSocket == null)
{
throw new InvalidOperationException("A mediaSession needs to have at least an audioSocket");
}
this._audioSocket.AudioMediaReceived += this.OnAudioMediaReceived;
this.videoSockets = mediaSession.VideoSockets?.ToList();
if (this.videoSockets?.Any() == true)
{
this.videoSockets.ForEach(videoSocket => videoSocket.VideoMediaReceived += this.OnVideoMediaReceived);
}
// Subscribe to the VBSS media.
this.vbssSocket = mediaSession.VbssSocket;
if (this.vbssSocket != null)
{
mediaSession.VbssSocket.VideoMediaReceived += this.OnVbssMediaReceived;
}
}
`
private ILocalMediaSession CreateLocalMediaSession(Guid mediaSessionId = default)
{
try
{
// create media session object, this is needed to establish call connections
var videoSocketSettings = new List<VideoSocketSettings>();
// create the receive only sockets settings for the multiview support
for (int i = 0; i < SampleConstants.NumberOfMultiviewSockets; i++)
{
videoSocketSettings.Add(new VideoSocketSettings
{
StreamDirections = StreamDirection.Recvonly,
ReceiveColorFormat = VideoColorFormat.H264,
});
}
// Create the VBSS socket settings
var vbssSocketSettings = new VideoSocketSettings
{
StreamDirections = StreamDirection.Recvonly,
ReceiveColorFormat = VideoColorFormat.H264,
MediaType = MediaType.Vbss,
SupportedSendVideoFormats = new List<VideoFormat>
{
// fps 1.875 is required for h264 in vbss scenario.
VideoFormat.H264_1920x1080_1_875Fps,
},
};
// create media session object, this is needed to establish call connections
var mediaSession = this.Client.CreateMediaSession(
new AudioSocketSettings
{
StreamDirections = StreamDirection.Recvonly,
SupportedAudioFormat = AudioFormat.Pcm16K,
},
videoSocketSettings,
vbssSocketSettings,
mediaSessionId: mediaSessionId);
return mediaSession;
}
catch (Exception e)
{
_logger.Log(System.Diagnostics.TraceLevel.Error, e.Message);
throw;
}
}
Here audio is getting processed from team-recording-bot
AudioProcessor code: `// ***********************************************************************
// Assembly : RecordingBot.Services
// Author : JasonTheDeveloper
// Created : 09-07-2020
//
// Last Modified By : dannygar
// Last Modified On : 09-07-2020
// ***********************************************************************
// <copyright file="AudioProcessor.cs" company="Microsoft">
// Copyright © 2020
// </copyright>
// <summary></summary>
// ***********************************************************************
using NAudio.Wave;
using RecordingBot.Model.Constants;
using RecordingBot.Services.Contract;
using RecordingBot.Services.ServiceSetup;
using RecordingBot.Services.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
namespace RecordingBot.Services.Media
{
/// <summary>
/// Class AudioProcessor.
/// Implements the <see cref="RecordingBot.Services.Util.BufferBase{RecordingBot.Services.Media.SerializableAudioMediaBuffer}" />
/// </summary>
/// <seealso cref="RecordingBot.Services.Util.BufferBase{RecordingBot.Services.Media.SerializableAudioMediaBuffer}" />
public class AudioProcessor : BufferBase<SerializableAudioMediaBuffer>
{
/// <summary>
/// The writers
/// </summary>
readonly Dictionary<string, WaveFileWriter> _writers = new Dictionary<string, WaveFileWriter>();
/// <summary>
/// The processor identifier
/// </summary>
private readonly string _processorId = null;
/// <summary>
/// The settings
/// </summary>
private readonly AzureSettings _settings;
/// <summary>
/// Initializes a new instance of the <see cref="AudioProcessor" /> class.
/// </summary>
/// <param name="settings">The settings.</param>
public AudioProcessor(IAzureSettings settings)
{
_processorId = Guid.NewGuid().ToString();
_settings = (AzureSettings)settings;
}
/// <summary>
/// Processes the specified data.
/// </summary>
/// <param name="data">The data.</param>
protected override async Task Process(SerializableAudioMediaBuffer data)
{
if (data.Timestamp == 0)
{
return;
}
var path = Path.Combine(Path.GetTempPath(), BotConstants.DefaultOutputFolder, _settings.MediaFolder, _processorId);
// First, write all audio buffer, unless the data.IsSilence is checked for true, into the all speakers buffer
var all = "all";
var all_writer = _writers.ContainsKey(all) ? _writers[all] : InitialiseWavFileWriter(path, all);
if (data.Buffer != null)
{
// Buffers are saved to disk even when there is silence.
// If you do not want this to happen, check if data.IsSilence == true.
await all_writer.WriteAsync(data.Buffer, 0, data.Buffer.Length).ConfigureAwait(false);
}
if (data.SerializableUnmixedAudioBuffers != null)
{
foreach (var s in data.SerializableUnmixedAudioBuffers)
{
if (string.IsNullOrWhiteSpace(s.AdId) || string.IsNullOrWhiteSpace(s.DisplayName))
{
continue;
}
var id = s.AdId;
var writer = _writers.ContainsKey(id) ? _writers[id] : InitialiseWavFileWriter(path, id);
// Write audio buffer into the WAV file for individual speaker
await writer.WriteAsync(s.Buffer, 0, s.Buffer.Length).ConfigureAwait(false);
// Write audio buffer into the WAV file for all speakers
await all_writer.WriteAsync(s.Buffer, 0, s.Buffer.Length).ConfigureAwait(false);
}
}
}
/// <summary>
/// Initialises the wav file writer.
/// </summary>
/// <param name="rootFolder">The root folder.</param>
/// <param name="id">The identifier.</param>
/// <returns>WavFileWriter.</returns>
private WaveFileWriter InitialiseWavFileWriter(string rootFolder, string id)
{
var path = AudioFileUtils.CreateFilePath(rootFolder, $"{id}.wav");
// Initialize the Wave Format using the default PCM 16bit 16K supported by Teams audio settings
var writer = new WaveFileWriter(path, new WaveFormat(
rate: AudioConstants.DefaultSampleRate,
bits: AudioConstants.DefaultBits,
channels: AudioConstants.DefaultChannels));
_writers.Add(id, writer);
return writer;
}
/// <summary>
/// Finalises the wav writing and returns a list of all the files created
/// </summary>
/// <returns>System.String.</returns>
public async Task<string> Finalise()
{
//drain the un-processed buffers on this object
while (Buffer.Count > 0)
{
await Task.Delay(200);
}
var archiveFile = Path.Combine(Path.GetTempPath(), BotConstants.DefaultOutputFolder, _settings.MediaFolder, _processorId, $"{Guid.NewGuid()}.zip");
try
{
using (var stream = File.OpenWrite(archiveFile))
{
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
// drain all the writers
foreach (var writer in _writers.Values)
{
var localFiles = new List<string>();
var localArchive = archive; //protect the closure below
var localFileName = writer.Filename;
localFiles.Add(writer.Filename);
await writer.FlushAsync();
writer.Dispose();
// Is Resampling and/or mono to stereo conversion required?
if (_settings.AudioSettings.WavSettings != null)
{
// The resampling is required
localFiles.Add(AudioFileUtils.ResampleAudio(localFileName, _settings.AudioSettings.WavSettings, _settings.IsStereo));
}
else if (_settings.IsStereo) // Is Stereo audio required?
{
// Convert mono WAV to stereo
localFiles.Add(AudioFileUtils.ConvertToStereo(localFileName));
}
// Remove temporary saved local WAV file from the disk
foreach (var localFile in localFiles)
{
await Task.Run(() =>
{
var fInfo = new FileInfo(localFile);
localArchive.CreateEntryFromFile(localFile, fInfo.Name, CompressionLevel.Optimal);
File.Delete(localFile);
}).ConfigureAwait(false);
}
}
}
}
}
finally
{
await End();
}
return archiveFile;
}
}
}
`
I request you to please help us on this. We need to get video from team-recording-bot and save it to local in.zip file and also to s3 bucket. Please, Please help us on this.
In my Vaadin 6 application I sometimes get the following error:
SEVERE: Terminal error:
java.lang.RuntimeException: handleURI for http://AAA.BBB.CCC.DDD:8080/myapp/ uri: '' returns ambigious result.
at com.vaadin.ui.Window.handleURI(Window.java:432)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleURI(AbstractCommunicationManager.java:2291)
at com.vaadin.terminal.gwt.server.CommunicationManager.handleURI(CommunicationManager.java:370)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.handleURI(AbstractApplicationServlet.java:1099)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(AbstractApplicationServlet.java:535)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Accrording to Vaadin source it occurs in the following method:
public DownloadStream handleURI(URL context, String relativeUri) {
DownloadStream result = null;
if (uriHandlerList != null) {
Object[] handlers;
synchronized (uriHandlerList) {
handlers = uriHandlerList.toArray();
}
for (int i = 0; i < handlers.length; i++) {
final DownloadStream ds = ((URIHandler) handlers[i]).handleURI(
context, relativeUri);
if (ds != null) {
if (result != null) {
throw new RuntimeException("handleURI for " + context
+ " uri: '" + relativeUri
+ "' returns ambigious result.");
}
result = ds;
}
}
}
return result;
}
I actually create a DownloadStream in a column generator (in order to display images in a table):
public class ImageColumnGenerator implements Table.ColumnGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageColumnGenerator.class);
public final static String IMAGE_FIELD = "image";
public Object generateCell(final Table aTable, final Object aItemId, final Object aColumnId) {
if (!IMAGE_FIELD.equals(aColumnId)) {
return null;
}
final BeanItem<UserProductImageBean> beanItem = (BeanItem<UserProductImageBean>)
aTable.getItem(aItemId);
final StreamResource streamResource = new StreamResource(new StreamResource.StreamSource() {
public InputStream getStream() {
return new ByteArrayInputStream(beanItem.getBean().getImageData());
}
},
beanItem.getBean().getFileName(),
MyApplication.getInstance());
LOGGER.debug("imageResource: " + streamResource);
final Embedded embedded = new Embedded("", streamResource);
return embedded;
}
}
beanItem.getBean().getImageData() is a byte array (byte[]) with image data, which I get from a web service.
MyApplication.getInstance() is defined as follows:
public class MyApplication extends Application implements ApplicationContext.TransactionListener
{
private static ThreadLocal<MyApplication> currentApplication =
new ThreadLocal<MyApplication> ();
public static MyApplication getInstance()
{
return currentApplication.get ();
}
}
What can I do in order to fix the aforementioned (severe) error?
As soon as nobody answer. I'm not at all expert in what hell it is above, but - try to find out on what kind of urls this error arise on, and do with them something before feed them to DownloadStream
I am trying to build a very simple XNA project.
Every 5 seconds a new ball should be spawned which will bounce of the walls.
For some reason it doesn't create multiple instances of my ball. I can't seem to figure out what i'm doing wrong.
Was hoping someone here could help me discover my errors.
Here is my code Game1.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace BallBounce
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
public static SpriteBatch spriteBatch;
Ball ball;
Ball ball2;
Ball[] balls;
int maxBalls = 1;
Texture2D ballTexture;
Texture2D ballTexture2;
Vector2 position;
Vector2 position2;
int spawnTime = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
ballTexture = Content.Load<Texture2D>("Bitmap1");
ballTexture2 = Content.Load<Texture2D>("Bitmap2");
Random r = new Random();
int randomNumberX = r.Next(0, 400);
int randomNumberY = r.Next(0, 400);
position = new Vector2(randomNumberX, randomNumberY);
position2 = new Vector2(randomNumberY, randomNumberX);
ball = new Ball(this, ballTexture, position);
ball2 = new Ball(this, ballTexture2, position2);
Components.Add(ball);
// Components.Add(ball2);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
spawnTime += (int)gameTime.ElapsedGameTime.Milliseconds;
// Console.WriteLine(spawnTime + " " + maxBalls);
if(spawnTime >= 500)
{
maxBalls += 1;
for(int i = 0; i < maxBalls; i++)
{
//balls[i] = new Ball(this,ballTexture);
//Components.Add(balls[i]);
}
spawnTime = 0;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
And here is my Ball.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace BallBounce
{
public class Ball : Microsoft.Xna.Framework.DrawableGameComponent
{
Texture2D texture;
Vector2 speed = new Vector2(4,6);
Vector2 position;
Color color = Color.Blue;
public Ball(Game1 game, Texture2D texture, Vector2 position)
: base(game)
{
this.texture = texture;
Console.WriteLine("=========================BAL---------------");
this.position = position;
Random random = new Random();
int red = random.Next(0, 255);
int green = random.Next(0,255);
int blue = random.Next(0,255);
color = new Color(red,green,blue);
Console.WriteLine(position);
}
public override void Update(GameTime gameTime)
{
this.position = this.position += speed;
if (this.position.Y >= (GraphicsDevice.Viewport.Height - this.texture.Height))
{
speed.Y = speed.Y * -1;
}
if (this.position.Y <= 0)
{
speed.Y = speed.Y * -1;
}
if (this.position.X >= (GraphicsDevice.Viewport.Width - this.texture.Width))
{
speed.X = speed.X * -1;
}
if (this.position.X <= 0)
{
speed.X = speed.X * -1;
}
}
public override void Draw(GameTime gameTime)
{
Game1.spriteBatch.Begin();
Game1.spriteBatch.Draw(texture, position, color);
Game1.spriteBatch.End();
base.Draw(gameTime);
}
}
}
It looks like you're recreating all balls in some array, adding one more every 500 milliseconds (which is 0.5 of a second really). You should just add a new ball to some global list of balls, instead of rewriting all existing balls as you do now.
So I guess you could do this:
if(spawnTime >= 500)
{
Components.Add(new Ball(this, ballTexture));
spawnTime = 0;
}
Your approach doesn't look good, though. Are you sure you want to add balls straight to Components?
Pretty new to monogame (mono for android to be precise) but with some youtube tutorials the process was fairly pain free.
I'm trying to override some functions (from an "XNA library project" dll) I can override all the functions just fine. But when I try to override anything that passes in a SpriteBatch as an argument I get the follow error:
Error 5 'Parkour.Screens.EditorScreen.Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch)':
no suitable method found to override D:\Data\programming and
such\comps\TIGsport\XNA\Parkour\Parkour\Parkour\Screens\EditorScreen.cs 117 30 ParkourAndroid
I'm absolutely sure the method is there, because the XNA project works just fine.
The Draw function also pops up in autocorrect in the mono for android project. But strange enough it seems to have dissapeared from autocorrect after I received the error.
Here is the entire class which holds the to be override function, just so you guys can be sure nothing is wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
namespace SimpleTilebasedLibrary.Utils
{
public class LoopContainer<T> where T : ILoopable
{
protected List<T> _items = new List<T>();
private List<T> _addList = new List<T>();
private List<T> _removeList = new List<T>();
public List<T> items
{
get{return _items;}
}
public virtual void add(T item)
{
//if (_addList.Contains(item)) return;
//_addList.Add(item);
_items.Add(item);
}
public virtual void remove(T item)
{
if (_removeList.Contains(item)) return;
_removeList.Add(item);
}
public T get(int index)
{
return _items[index];
}
public T get(string name)
{
foreach (T item in items)
{
if (item.getName() == name)
{
return item;
}
}
return default(T);
}
public virtual void Update()
{
items.AddRange(_addList);
_addList.Clear();
foreach (T item in items)
{
if (item.status == Status.DEAD)
{
_removeList.Add(item);
//break; //root of all evil
continue;
}
item.Update();
}
//remove
foreach (T i in _removeList)
{
items.Remove(i);
}
_removeList.Clear();
}
public virtual void postUpdate()
{
foreach (T item in items)
{
item.postUpdate();
}
}
public virtual void Draw(SpriteBatch spritebatch)
{
foreach (T item in items)
{
item.Draw(spritebatch);
}
}
}
}
And the class that is trying to override it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleTilebasedLibrary;
using SimpleTilebasedLibrary.Entities;
using SimpleTilebasedLibrary.Tilesystem;
using SimpleTilebasedLibrary.Services;
using Microsoft.Xna.Framework.Input;
using SimpleTilebasedLibrary.Components;
using SimpleTilebasedLibrary.Utils;
using SimpleTilebasedLibrary.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Parkour.Screens
{
public class EditorScreen : GameScreen //need to couple gamescreens with inputcontexts?
{
public ParkourWorld world;
int currentTile = 0;
GameObject tile;
Checkbox editorEnabled;
Checkbox solidCB;
Checkbox autotileCB;
public EditorScreen(ParkourWorld world)
: base("editorscreen")
{
this.world = world;
tile = new GameObject("tileset", 16, 16); //never actually tested this, doesn't work!
tile.GetC<GraphicsC>().setScale(2, 2);
//add(tile); //something fucks up the coordinates when you add it...
editorEnabled = new Checkbox(Color.White, 10);
editorEnabled.GetC<TransformC>().Y = 10;
editorEnabled.GetC<TransformC>().X = 100;
solidCB = new Checkbox(Color.Red, 10);
solidCB.GetC<TransformC>().Y = 10;//30;
solidCB.GetC<TransformC>().X = 120;
//add(solidCB);
autotileCB = new Checkbox(Color.Blue, 10);
autotileCB.GetC<TransformC>().Y = 10;//50;
autotileCB.GetC<TransformC>().X = 140;
//add(autotileCB);
editorEnabled.value = false;
}
public override void Update()
{
base.Update();
if (GameServices.get<InputManager>().hasScrolledDown() && currentTile > 0)
{
currentTile--;
}
if (GameServices.get<InputManager>().hasScrolledUp() && currentTile < tile.GetC<GraphicsC>().totalFrames - 1)
{
currentTile++;
Console.WriteLine(currentTile);
}
tile.GetC<GraphicsC>().gotoAndStop(currentTile);
//
if (Mouse.GetState().LeftButton == ButtonState.Pressed && editorEnabled.value)
{
GameCamera camera = GameServices.get<CameraManager>().getActiveCamera();
int x = TileMath.PixelToTile((Mouse.GetState().X + (camera.GetC<CameraC>().leftX * camera.GetC<CameraC>().zoom)) / camera.GetC<CameraC>().zoom, world.tilegrid.tileWidth);
int y = TileMath.PixelToTile((Mouse.GetState().Y + (camera.GetC<CameraC>().UpY * camera.GetC<CameraC>().zoom)) / camera.GetC<CameraC>().zoom, world.tilegrid.tileHeight);
if (Keyboard.GetState().IsKeyDown(Keys.Z))
{
world.tilegrid.setTile(x, y, 0, null);
//world.tilegrid.getTile(x, y, 0).id = 1;
//world.tilegrid.getTile(x, y, 0).solid = false;
}
else
{
Tile t = world.tilegrid.setTile(x, y, 0, currentTile);
if (t != null) t.solid = solidCB.value;
if(autotileCB.value)world.tilegrid.AutoTile(t, 0, x, y, true);
//world.tilegrid.setTile(x, y, 0, null);
}
}
// enable and disable cb's //
if (GameServices.get<InputManager>().wasKeyPressed(Keys.LeftShift))
{
solidCB.value = !solidCB.value;
}
if (GameServices.get<InputManager>().wasKeyPressed(Keys.Q))
{
autotileCB.value = !autotileCB.value;
}
if (GameServices.get<InputManager>().wasKeyPressed(Keys.E))
{
editorEnabled.value = !editorEnabled.value;
}
solidCB.Update();
autotileCB.Update();
}
public override void Draw(SpriteBatch spritebatch)
{
base.Draw(spritebatch);
tile.Draw(spritebatch);
editorEnabled.Draw(spritebatch);
solidCB.Draw(spritebatch);
autotileCB.Draw(spritebatch);
CameraC camera = GameServices.get<CameraManager>().getActiveCameraC();
int width = TileMath.PixelToTile(camera.viewrect.Left + camera.viewrect.Width + (world.tilegrid.tileWidth * 2), world.tilegrid.tileWidth);
int height = TileMath.PixelToTile(camera.viewrect.Top + camera.viewrect.Height + (world.tilegrid.tileHeight * 2), world.tilegrid.tileHeight);
if (editorEnabled.value)
{
spritebatch.End();
spritebatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, GameServices.get<CameraManager>().getActiveCameraC().getTransformation());
//getTile(width - 1, 0).GetComponent<GraphicsC>().sprite.gotoAndStop(4);
Rectangle rect = new Rectangle();
Color trans = new Color(255, 0, 0, 10);
for (int x = TileMath.PixelToTile(camera.viewrect.Left, world.tilegrid.tileWidth); x < width; x++)
{
for (int y = TileMath.PixelToTile(camera.viewrect.Top, world.tilegrid.tileHeight); y < height; y++)
{
if (world.tilegrid.getTile(x, y, 0) != null)
{
if (!world.tilegrid.getTile(x, y, 0).solid) continue;
rect.X = x * world.tilegrid.tileWidth;
rect.Y = y * world.tilegrid.tileHeight;
rect.Width = world.tilegrid.tileWidth;
rect.Height = world.tilegrid.tileHeight;
spritebatch.Draw(GameServices.get<AssetManager>().CreateColoredTexture(trans), rect, Color.White);
}
}
}
spritebatch.End();
spritebatch.Begin();
}
}
}
}
There is alot of useless stuff in there for you guys, but I wanted to include it just for the sake of completeness.
I have the exact same problem with another class that has a Draw(SpriteBatch) function that needs to be overriden.
Turned out that I was passing in a MonoGame spritebatch where the library was requiring an XNA spritebatch. I recompiled the library in a seperate project with MonoGame and all problems are sovled.
I'm trying to print XPS documents from a windows service on the .net framework. Since Microsoft does not support printing by using System.Drawing.Printing nor by using System.Printing (WPF), I'm using the native XPSPrint API.
This is suggested to me by Aspose in http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/howto-print-a-document-on-a-server-via-the-xpsprint-api.html.
When I try to print an XPS document from a windows service, the result contains strange characters instead of the text I want.
I tried with different printers (including virtual printers like for instance PDFCreator), different users and user-privileges for the service, different xps generators (aspose, word 2007, word 2010), different platforms (windows 7, windows 2008 R2) but all have the same result.
Does anybody knows how to solve this? Any help would be appreciated!
For those who want to try it, I shared some files via:
https://docs.google.com/leaf?id=0B4J93Ly5WzQKNWU2ZjM0MDYtMjFiMi00NzM0LTg4MTgtYjVlNDA5NWQyMTc3&hl=nl
document.xps: the XPS document to print
document_printed_to_pdfcreator.pdf: the printed document that demonstrates what is going wrong
XpsPrintTest.zip: a sample VS2010 solution with the sample code
The sample code for the managed windows service is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
namespace PrintXpsService
{
public partial class XpsPrintService : ServiceBase
{
// Change name of printer here
private String f_printerName = "PDFCreator";
// path to some file where logging is done
private String f_logFile = #"C:\temp\testdoc\xps_printing_service_log.txt";
// path to xps file to print
private String f_xpsFile = #"C:\temp\testdoc\document.xps";
public XpsPrintService()
{
InitializeComponent();
}
private void Log(String fmt, params Object[] args)
{
try
{
DateTime now = DateTime.Now;
using (StreamWriter wrt = new StreamWriter(f_logFile, true))
{
wrt.Write("{0} {1} - ", now.ToShortDateString(), now.ToShortTimeString());
wrt.WriteLine(fmt, args);
}
}
catch (Exception ex)
{
}
}
protected override void OnStart(string[] args)
{
// uncomment to allow to connect debugger
//int i = 0;
//while (i == 0)
//{
// if (i == 0)
// {
// Thread.Sleep(1000);
// }
//}
Log("Starting Service");
try
{
Log("Printing xps file {0}", f_xpsFile);
using (Stream stream = new FileStream(f_xpsFile, FileMode.Open, FileAccess.Read))
{
Log("Starting to print on printer {0}", f_printerName);
String jobName = f_xpsFile;
this.Print(stream, jobName);
}
Log("Document printed");
}
catch (Exception ex)
{
Log("Exception during execution: {0}", ex.Message);
Log(" {0}", ex.StackTrace);
Exception inner = ex.InnerException;
while (inner != null)
{
Log("=== Inner Exception: {0}", inner.Message);
Log(" {0}", inner.StackTrace);
inner = inner.InnerException;
}
}
}
protected override void OnStop()
{
}
public void Print(Stream stream, String jobName)
{
String printerName = f_printerName;
IntPtr completionEvent = CreateEvent(IntPtr.Zero, true, false, null);
try
{
IXpsPrintJob job;
IXpsPrintJobStream jobStream;
StartJob(printerName, jobName, completionEvent, out job, out jobStream);
CopyJob(stream, job, jobStream);
WaitForJob(completionEvent, -1);
CheckJobStatus(job);
}
finally
{
if (completionEvent != IntPtr.Zero)
CloseHandle(completionEvent);
}
}
private void StartJob(String printerName,
String jobName, IntPtr completionEvent,
out IXpsPrintJob job,
out IXpsPrintJobStream jobStream)
{
int result = StartXpsPrintJob(printerName, jobName, null, IntPtr.Zero, completionEvent,
null, 0, out job, out jobStream, IntPtr.Zero);
if (result != 0)
throw new Win32Exception(result);
}
private void CopyJob(Stream stream, IXpsPrintJob job, IXpsPrintJobStream jobStream)
{
try
{
byte[] buff = new byte[4096];
while (true)
{
uint read = (uint)stream.Read(buff, 0, buff.Length);
if (read == 0)
break;
uint written;
jobStream.Write(buff, read, out written);
if (read != written)
throw new Exception("Failed to copy data to the print job stream.");
}
// Indicate that the entire document has been copied.
jobStream.Close();
}
catch (Exception)
{
// Cancel the job if we had any trouble submitting it.
job.Cancel();
throw;
}
}
private void WaitForJob(IntPtr completionEvent, int timeout)
{
if (timeout < 0)
timeout = -1;
switch (WaitForSingleObject(completionEvent, timeout))
{
case WAIT_RESULT.WAIT_OBJECT_0:
// Expected result, do nothing.
break;
case WAIT_RESULT.WAIT_TIMEOUT:
// timeout expired
throw new Exception("Timeout expired");
case WAIT_RESULT.WAIT_FAILED:
throw new Exception("Wait for the job to complete failed");
default:
throw new Exception("Unexpected result when waiting for the print job.");
}
}
private void CheckJobStatus(IXpsPrintJob job)
{
XPS_JOB_STATUS jobStatus;
job.GetJobStatus(out jobStatus);
switch (jobStatus.completion)
{
case XPS_JOB_COMPLETION.XPS_JOB_COMPLETED:
// Expected result, do nothing.
break;
case XPS_JOB_COMPLETION.XPS_JOB_IN_PROGRESS:
// expected, do nothing, can occur when printer is paused
break;
case XPS_JOB_COMPLETION.XPS_JOB_FAILED:
throw new Win32Exception(jobStatus.jobStatus);
default:
throw new Exception("Unexpected print job status.");
}
}
[DllImport("XpsPrint.dll", EntryPoint = "StartXpsPrintJob")]
private static extern int StartXpsPrintJob(
[MarshalAs(UnmanagedType.LPWStr)] String printerName,
[MarshalAs(UnmanagedType.LPWStr)] String jobName,
[MarshalAs(UnmanagedType.LPWStr)] String outputFileName,
IntPtr progressEvent, // HANDLE
IntPtr completionEvent, // HANDLE
[MarshalAs(UnmanagedType.LPArray)] byte[] printablePagesOn,
UInt32 printablePagesOnCount,
out IXpsPrintJob xpsPrintJob,
out IXpsPrintJobStream documentStream,
IntPtr printTicketStream); // This is actually "out IXpsPrintJobStream", but we don't use it and just want to pass null, hence IntPtr.
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
[DllImport("Kernel32.dll", SetLastError = true, ExactSpelling = true)]
private static extern WAIT_RESULT WaitForSingleObject(IntPtr handle, Int32 milliseconds);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
}
/// <summary>
/// This interface definition is HACKED.
///
/// It appears that the IID for IXpsPrintJobStream specified in XpsPrint.h as
/// MIDL_INTERFACE("7a77dc5f-45d6-4dff-9307-d8cb846347ca") is not correct and the RCW cannot return it.
/// But the returned object returns the parent ISequentialStream inteface successfully.
///
/// So the hack is that we obtain the ISequentialStream interface but work with it as
/// with the IXpsPrintJobStream interface.
/// </summary>
[Guid("0C733A30-2A1C-11CE-ADE5-00AA0044773D")] // This is IID of ISequenatialSteam.
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IXpsPrintJobStream
{
// ISequentualStream methods.
void Read([MarshalAs(UnmanagedType.LPArray)] byte[] pv, uint cb, out uint pcbRead);
void Write([MarshalAs(UnmanagedType.LPArray)] byte[] pv, uint cb, out uint pcbWritten);
// IXpsPrintJobStream methods.
void Close();
}
[Guid("5ab89b06-8194-425f-ab3b-d7a96e350161")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IXpsPrintJob
{
void Cancel();
void GetJobStatus(out XPS_JOB_STATUS jobStatus);
}
[StructLayout(LayoutKind.Sequential)]
struct XPS_JOB_STATUS
{
public UInt32 jobId;
public Int32 currentDocument;
public Int32 currentPage;
public Int32 currentPageTotal;
public XPS_JOB_COMPLETION completion;
public Int32 jobStatus; // UInt32
};
enum XPS_JOB_COMPLETION
{
XPS_JOB_IN_PROGRESS = 0,
XPS_JOB_COMPLETED = 1,
XPS_JOB_CANCELLED = 2,
XPS_JOB_FAILED = 3
}
enum WAIT_RESULT
{
WAIT_OBJECT_0 = 0,
WAIT_ABANDONED = 0x80,
WAIT_TIMEOUT = 0x102,
WAIT_FAILED = -1 // 0xFFFFFFFF
}
}
Note: some links for more information:
MS not supporting printing from managed code: http://support.microsoft.com/kb/324565 , http://msdn.microsoft.com/en-us/library/system.drawing.printing.aspx and http://msdn.microsoft.com/en-us/library/bb613549.aspx
XPSPrint API: http://msdn.microsoft.com/en-us/library/dd374565(VS.85).aspx
I talked with microsoft about this issue and we discovered the problem is related to incorrect font substitution in the printer-spooler. When the printer is set to not spool the documents, they are printed correctly, also from a windows service. Otherwise, all fonts, except arial (and maybe some others), are substituted by another font. In the sample I provided, calibri is substituted by wingdings.
So, they acknowledge this to be a bug but at the moment they will not resolve it. It will depend on how many people will suffer from this bug in order for them to decide whether are not they are willing to fix it...