Search Results

Search found 2978 results on 120 pages for 'ex parrot'.

Page 5/120 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Problems installing LYNC on non-domain controler

    - by Trikks
    I have two servers in this set up. AD and EX, the domain is called mydomain.net The AD is a Windows 2008 Server (32 bit) with Active Directory installed AD only has it's own ip in the DNS-servers list AD.mydomain.net does resolve correctly in the dns EX is a Windows 2008 R2 that is connected to the mydomain.net-domain EX only DNS server is the ip of the ad.mydomain.net There are no firewalls running between the two servers When trying to install Lync 2010 on the EX server I get the following error "Not available :Failure occurred attempting to check the schema state.Please ensure Active Directory is reachable." I can control the AD from EX, also login to it and do successful checks like netdom query /domain:mydomain.net fsmo ...that resolves correctly I suspect there is something fundamentally wrong with my setup, maybe Lync need a 2k8 R2 ad?

    Read the article

  • Feed Reader Fix

    - by Geertjan
    In the FeedReader sample (available in the New Projects window), there's this piece of code: private static Feed getFeed(Node node) { InstanceCookie ck = node.getLookup().lookup(InstanceCookie.class); if (ck == null) { throw new IllegalStateException("Bogus file in feeds folder: " + node.getLookup().lookup(FileObject.class)); } try { return (Feed) ck.instanceCreate(); } catch (ClassNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } Since 7.1, for some reason, the above doesn't work. What does work, and is simpler, is this, instead of the above: private static Feed getFeed(Node node) { Feed f = FileUtil.getConfigObject("RssFeeds/sample.instance", Feed.class); if (f == null) { throw new IllegalStateException("Bogus file in feeds folder: " + node.getLookup().lookup(FileObject.class)); } return f; } So, the code needs to be fixed in the sample.

    Read the article

  • How do I put different textures on different walls? LWJGL

    - by lehermj
    So far I have it so you are running around in a box, but all of the walls are the same texture! I've loaded up other textures for the walls (I want the walls a different texture than the floor) but it seems as if its being ignored... Here's my code: int floorTexture = glGenTextures(); { InputStream in = null; try { in = new FileInputStream("floor.png"); PNGDecoder decoder = new PNGDecoder(in); ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA); buffer.flip(); glBindTexture(GL_TEXTURE_2D, floorTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glBindTexture(GL_TEXTURE_2D, floorTexture); } catch (FileNotFoundException ex) { System.err.println("Failed to find the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } catch (IOException ex) { System.err.println("Failed to load the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } int wallTexture = glGenTextures(); { InputStream in = null; try { in = new FileInputStream("walls.png"); PNGDecoder decoder = new PNGDecoder(in); ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA); buffer.flip(); glBindTexture(GL_TEXTURE_2D, wallTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glBindTexture(GL_TEXTURE_2D, wallTexture); } catch (FileNotFoundException ex) { System.err.println("Failed to find the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } catch (IOException ex) { System.err.println("Failed to load the texture files."); ex.printStackTrace(); Display.destroy(); System.exit(1); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } int ceilingDisplayList = glGenLists(1); glNewList(ceilingDisplayList, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, ceilingHeight, gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, ceilingHeight, gridSize); glEnd(); glEndList(); int wallDisplayList = glGenLists(1); glNewList(wallDisplayList, GL_COMPILE); glBegin(GL_QUADS); // North wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); // West wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(-gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, floorHeight, +gridSize); // East wall glTexCoord2f(0, 0); glVertex3f(+gridSize, floorHeight, -gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(+gridSize, floorHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, -gridSize); // South wall glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(-gridSize, ceilingHeight, +gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(+gridSize, ceilingHeight, +gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(+gridSize, floorHeight, +gridSize); glEnd(); glEndList(); int floorDisplayList = glGenLists(1); glNewList(floorDisplayList, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-gridSize, floorHeight, -gridSize); glTexCoord2f(0, gridSize * 10 * tileSize); glVertex3f(-gridSize, floorHeight, gridSize); glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize); glVertex3f(gridSize, floorHeight, gridSize); glTexCoord2f(gridSize * 10 * tileSize, 0); glVertex3f(gridSize, floorHeight, -gridSize); glEnd(); glEndList();

    Read the article

  • Configurable Values in Enum

    - by Omer Akhter
    I often use this design in my code to maintain configurable values. Consider this code: public enum Options { REGEX_STRING("Some Regex"), REGEX_PATTERN(Pattern.compile(REGEX_STRING.getString()), false), THREAD_COUNT(2), OPTIONS_PATH("options.config", false), DEBUG(true), ALWAYS_SAVE_OPTIONS(true), THREAD_WAIT_MILLIS(1000); Object value; boolean saveValue = true; private Options(Object value) { this.value = value; } private Options(Object value, boolean saveValue) { this.value = value; this.saveValue = saveValue; } public void setValue(Object value) { this.value = value; } public Object getValue() { return value; } public String getString() { return value.toString(); } public boolean getBoolean() { Boolean booleanValue = (value instanceof Boolean) ? (Boolean) value : null; if (value == null) { try { booleanValue = Boolean.valueOf(value.toString()); } catch (Throwable t) { } } // We want a NullPointerException here return booleanValue.booleanValue(); } public int getInteger() { Integer integerValue = (value instanceof Number) ? ((Number) value).intValue() : null; if (integerValue == null) { try { integerValue = Integer.valueOf(value.toString()); } catch (Throwable t) { } } return integerValue.intValue(); } public float getFloat() { Float floatValue = (value instanceof Number) ? ((Number) value).floatValue() : null; if (floatValue == null) { try { floatValue = Float.valueOf(value.toString()); } catch (Throwable t) { } } return floatValue.floatValue(); } public static void saveToFile(String path) throws IOException { FileWriter fw = new FileWriter(path); Properties properties = new Properties(); for (Options option : Options.values()) { if (option.saveValue) { properties.setProperty(option.name(), option.getString()); } } if (DEBUG.getBoolean()) { properties.list(System.out); } properties.store(fw, null); } public static void loadFromFile(String path) throws IOException { FileReader fr = new FileReader(path); Properties properties = new Properties(); properties.load(fr); if (DEBUG.getBoolean()) { properties.list(System.out); } Object value = null; for (Options option : Options.values()) { if (option.saveValue) { Class<?> clazz = option.value.getClass(); try { if (String.class.equals(clazz)) { value = properties.getProperty(option.name()); } else { value = clazz.getConstructor(String.class).newInstance(properties.getProperty(option.name())); } } catch (NoSuchMethodException ex) { Debug.log(ex); } catch (InstantiationException ex) { Debug.log(ex); } catch (IllegalAccessException ex) { Debug.log(ex); } catch (IllegalArgumentException ex) { Debug.log(ex); } catch (InvocationTargetException ex) { Debug.log(ex); } if (value != null) { option.setValue(value); } } } } } This way, I can save and retrieve values from files easily. The problem is that I don't want to repeat this code everywhere. Like as we know, enums can't be extended; so wherever I use this, I have to put all these methods there. I want only to declare the values and that if they should be persisted. No method definitions each time; any ideas?

    Read the article

  • Java exception handling in non sequential tasks (pattern/good practice)

    - by Hernán Eche
    There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...) But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc.. For that kind of tasks, I would like to know a java best practice or pattern for manage exceptions.. The java simple way is: getUFO { try { loadSoundDriver(); loadUsbDriver(); loadAlienDetectorDriver(); loadKeyboardDriver(); } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } But what about having an exception in one of the actions but wanting to try with the next ones?? I've thought this approach, but don't seem to be a good use for exceptions I don't know if it works, doesn't matter, it's really awful!! getUFO { Exception ex=null; try { try{ loadSoundDriver(); }catch (Exception e) { ex=e; } try{ loadUsbDriver(); }catch (Exception e) { ex=e; } try{ loadAlienDetectorDriver(); }catch (Exception e) { ex=e; } try{ loadKeyboardDriver() }catch (Exception e) { ex=e; } close the file; if(ex!=null) { throw ex; } } catch (loadSoundDriverFailed) { doSomethingA; } catch (loadUsbDriverFailed) { doSomethingB; } catch (loadAlienDetectorDriverFailed) { doSomethingC; } catch (loadKeyboardDriverFailed) { doSomethingD; } } seems not complicated to find a better practice for doing that.. I still didn't thanks for any advice

    Read the article

  • Handling exceptions in Prism 4 modules

    - by marcellscarlett
    I've gone through a number of threads here about this topic with no success. It seems that in the App.xaml.cs of our WPF application, handling DispatcherUnhandledExceptions and AppDomain.CurrentDomain.UnhandledException don't catch everything. In this specific instance we have 7 prism modules. My exception handling code is below (almost identical for UnhandledException): private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { try { var ex = e.Exception.InnerException ?? e.Exception; var logManager = new LogManager(); logManager.Error(ex); if (!EventLog.SourceExists(ex.Source)) EventLog.CreateEventSource(ex.Source, "AppName"); EventLog.WriteEntry(ex.Source, ex.InnerException.ToString()); var emb = new ExceptionMessageBox(ex); emb.ShowDialog(); e.Handled = true; } catch (Exception) { } } The problem seems to be the unhandled exceptions occurring in the modules. They aren't caught by the code above and they cause the application to crash without logging or displaying any sort of message. Does anyone have experience with this?

    Read the article

  • Quartz scheduler is failing to start the cron job

    - by Amit
    Hi I am using Quartz scheduler to trigger a cron which needs to perform a host of activities. My Code for the same is as follow: In the init() method of my InitServlet class, I am defining my TimerServer public class InitServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { try { System.out.println("Starting the CRON"); //Set the DSO Handler CRON TimerServer task = TimerServer.getInstance(); task.setTask(); } catch (Exception ex) { System.out.println("Failed to start the cron"); ex.printStackTrace(); } } In my TimerServer class I have the following methods public void setTask() { try{ this.setSubscriptionDailyJob(); } catch(SchedulerException ex) { log.error("SchedulerException: "+ex.getMessage(), ex); } private void setSubscriptionDailyJob() throws SchedulerException { log.info("Step 1 "); Scheduler scheduler = schedulerFactory.getScheduler(); log.info("Step 2 "); JobDetail subscriptionJob = new JobDetail("subscription", "subscriptiongroup", SubscriptionDaily.class); log.info("Step 3 "); // Initiate CronTrigger with its name and group name CronTrigger subscriptionCronTrigger = new CronTrigger("subscriptionCronTrigger", "subscriptionTriggerGroup"); try { log.info("Subscription cron: "+Constants.SUBSCRIPTION_CRON); // setup CronExpression CronExpression cexp = new CronExpression(Constants.SUBSCRIPTION_CRON); // Assign the CronExpression to CronTrigger subscriptionCronTrigger.setCronExpression(cexp); } catch (Exception ex) { log.warn("Exception: "+ex.getMessage(), ex); } scheduler.scheduleJob(subscriptionJob, subscriptionCronTrigger); scheduler.start(); } In my SubscriptionDaily class : public class SubscriptionDaily implements Job { public void execute(JobExecutionContext arg0) throws JobExecutionException { //Actions to be performed } } Now checking my logs, I am getting Step 1, Step 2 but not further. My code is getting stucked at the TimerServer class itself. Logs wrt to Scheduler are : 17:24:43 INFO [TimerServer]: Step 1 17:24:43 INFO [SimpleThreadPool]: Job execution threads will use class loader of thread: http-8080-1 17:24:43 INFO [SchedulerSignalerImpl]: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl 17:24:43 INFO [QuartzScheduler]: Quartz Scheduler v.1.6.5 created. 17:24:43 INFO [RAMJobStore]: RAMJobStore initialized. 17:24:43 INFO [StdSchedulerFactory]: Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties' 17:24:43 INFO [StdSchedulerFactory]: Quartz scheduler version: 1.6.5 17:24:43 INFO [TimerServer]: Step 2 I think a log entry is missing : [QuartzScheduler]: Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. Please help.

    Read the article

  • How to send audio stream via UDP in java?

    - by Nob Venoda
    Hi to all :) I have a problem, i have set MediaLocator to microphone input, and then created Player. I need to grab that sound from the microphone, encode it to some lower quality stream, and send it as a datagram packet via UDP. Here's the code, i found most of it online and adapted it to my app: public class AudioSender extends Thread { private MediaLocator ml = new MediaLocator("javasound://44100"); private DatagramSocket socket; private boolean transmitting; private Player player; TargetDataLine mic; byte[] buffer; private AudioFormat format; private DatagramSocket datagramSocket(){ try { return new DatagramSocket(); } catch (SocketException ex) { return null; } } private void startMic() { try { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); mic = (TargetDataLine) AudioSystem.getLine(info); mic.open(format); mic.start(); buffer = new byte[1024]; } catch (LineUnavailableException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } private Player createPlayer() { try { return Manager.createRealizedPlayer(ml); } catch (IOException ex) { return null; } catch (NoPlayerException ex) { return null; } catch (CannotRealizeException ex) { return null; } } private void send() { try { mic.read(buffer, 0, 1024); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91); socket.send(packet); } catch (IOException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void run() { player = createPlayer(); player.start(); socket = datagramSocket(); transmitting = true; startMic(); while (transmitting) { send(); } } public static void main(String[] args) { AudioSender as = new AudioSender(); as.start(); } } And only thing that happens when I run the receiver class, is me hearing this Player from the sender class. And I cant seem to see the connection between TargetDataLine and Player. Basically, I need to get the sound form player, and somehow convert it to bytes[], therefore I can sent it as datagram. Any ideas? Everything is acceptable, as long as it works :)

    Read the article

  • How to use parallel execution in a shell script?

    - by eSKay
    I have a C shell script that does something like this: #!/bin/csh gcc example.c -o ex gcc combine.c -o combine ex file1 r1 <-- 1 ex file2 r2 <-- 2 ex file3 r3 <-- 3 #... many more like the above combine r1 r2 r3 final \rm r1 r2 r3 Is there some way I can make lines 1, 2 and 3 run in parallel instead of one after the another?

    Read the article

  • How to verify if the private key matches with the certificate..?

    - by surendhar_s
    I have the private key stored as .key file.. -----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQD5YBS6V3APdgqaWAkijIUHRK4KQ6eChSaRWaw9L/4u8o3T1s8J rUFHQhcIo5LPaQ4BrIuzHS8yzZf0m3viCTdZAiDn1ZjC2koquJ53rfDzqYxZFrId 7a4QYUCvM0gqx5nQ+lw1KoY/CDAoZN+sO7IJ4WkMg5XbgTWlSLBeBg0gMwIDAQAB AoGASKDKCKdUlLwtRFxldLF2QPKouYaQr7u1ytlSB5QFtIih89N5Avl5rJY7/SEe rdeL48LsAON8DpDAM9Zg0ykZ+/gsYI/C8b5Ch3QVgU9m50j9q8pVT04EOCYmsFi0 DBnwNBRLDESvm1p6NqKEc7zO9zjABgBvwL+loEVa1JFcp5ECQQD9/sekGTzzvKa5 SSVQOZmbwttPBjD44KRKi6LC7rQahM1PDqmCwPFgMVpRZL6dViBzYyWeWxN08Fuv p+sIwwLrAkEA+1f3VnSgIduzF9McMfZoNIkkZongcDAzjQ8sIHXwwTklkZcCqn69 qTVPmhyEDA/dJeAK3GhalcSqOFRFEC812QJAXStgQCmh2iaRYdYbAdqfJivMFqjG vgRpP48JHUhCeJfOV/mg5H2yDP8Nil3SLhSxwqHT4sq10Gd6umx2IrimEQJAFNA1 ACjKNeOOkhN+SzjfajJNHFyghEnJiw3NlqaNmEKWNNcvdlTmecObYuSnnqQVqRRD cfsGPU661c1MpslyCQJBAPqN0VXRMwfU29a3Ve0TF4Aiu1iq88aIPHsT3GKVURpO XNatMFINBW8ywN5euu8oYaeeKdrVSMW415a5+XEzEBY= -----END RSA PRIVATE KEY----- And i extracted public key from ssl certificate file.. Below is the code i tried to verify if private key matches with ssl certificate or not.. I used the modulus[i.e. private key get modulus==public key get modulus] to check if they are matching.. And this seems to hold only for RSAKEYS.. But i want to check for other keys as well.. Is there any other alternative to do the same..?? private static boolean verifySignature(File serverCertificateFile, File serverCertificateKey) { try { byte[] certificateBytes = FileUtils.readFileToByteArray(serverCertificateFile); //byte[] keyBytes = FileUtils.readFileToByteArray(serverCertificateKey); RandomAccessFile raf = new RandomAccessFile(serverCertificateKey, "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); raf.close(); PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf); KeyFactory kf; try { kf = KeyFactory.getInstance("RSA"); RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(kspec); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(certificateBytes); //Generate Certificate in X509 Format X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey(); in.close(); return privKey.getModulus() == publicKey.getModulus(); } catch (NoSuchAlgorithmException ex) { logger.log(Level.SEVERE, "Such algorithm is not found", ex); } catch (CertificateException ex) { logger.log(Level.SEVERE, "certificate exception", ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(CertificateConversion.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { logger.log(Level.SEVERE, "Signature verification failed.. This could be because the file is in use", ex); } return false; } And the code isn't working either.. throws invalidkeyspec exception

    Read the article

  • jframe adding own design jinternal frame error

    - by Van Minh
    I designed a title bar color on my JInternal frame. Then I took attempt to add it to my JFrame, but I cannot. Here is the code of my title bar: public class MyIFtitleBar extends BasicInternalFrameTitlePane { public MyIFtitleBar(JInternalFrame jif) { super(jif); } protected void paintTitleBackground(Graphics g){ g.setColor(Color.pink); g.fillRect(0, 0, getWidth(), getHeight()); } } Here is my JInternal frame. I tried running it in its psvm method, that worked! public class FitnessProg_Frame extends javax.swing.JInternalFrame { public FitnessProg_Frame() { initComponents(); this.setUI(new BasicInternalFrameUI(this){ @Override protected JComponent createNorthPane(JInternalFrame jif) { return new MyIFtitleBar(jif); } }); } @SuppressWarnings("unchecked") private void initComponents() { setBackground(new java.awt.Color(255, 255, 255)); setBorder(new javax.swing.border.MatteBorder(null)); setTitle("Fitness Progarm"); setPreferredSize(new java.awt.Dimension(507, 304)); pack(); } } But when I add it to my JFrame I get an error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Here is my JFrame code: public class NewJFrame extends javax.swing.JFrame { public NewJFrame() { initComponents(); FitnessProg_Frame ff = new FitnessProg_Frame(); ff.setVisible(true); mydes.add(ff); // this line made errors } @SuppressWarnings("unchecked") private void initComponents() { mydes = new javax.swing.JDesktopPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout mydesLayout = new javax.swing.GroupLayout(mydes); mydes.setLayout(mydesLayout); mydesLayout.setHorizontalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); mydesLayout.setVerticalGroup( mydesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); getContentPane().add(mydes, java.awt.BorderLayout.CENTER); pack(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } private javax.swing.JDesktopPane mydes; }

    Read the article

  • What's Wrong With My VB.NET Code Of Windows Forms Application?

    - by Krishanu Dey
    I've to forms frmPrint & frmEmail and a dataset(MyDataset) with some DataTable and DataTable Adapters. In frmPrint I've the following Sub Public Sub StartPrinting() try adapterLettersInSchedules.Fill(ds.LettersInSchedules) adapterLetters.Fill(ds.Letters) adapterClients.Fill(ds.Clients) adapterPrintJobs.GetPrintJobsDueToday(ds.PrintJobs, False, DateTime.Today) For Each prow As MyDataSet.PrintJobsRow In ds.PrintJobs Dim lisrow As MyDataSet.LettersInSchedulesRow = ds.LettersInSchedules.FindByID(prow.LetterInScheduleID) If lisrow.Isemail = False Then Dim clientrow As MyDataSet.ClientsRow = ds.Clients.FindByClientID(prow.ClientID) Dim letterrow As MyDataSet.LettersRow = ds.Letters.FindByID(lisrow.LetterID) 'prow. 'lisrow.is Label1.SuspendLayout() Label1.Refresh() Label1.Text = "Printing letter" txt.Rtf = letterrow.LetterContents txt.Rtf = txt.Rtf.Replace("<%Firstname%>", clientrow.FirstName) txt.Rtf = txt.Rtf.Replace("<%Lastname%>", clientrow.LastName) txt.Rtf = txt.Rtf.Replace("<%Title%>", clientrow.Title) txt.Rtf = txt.Rtf.Replace("<%Street%>", clientrow.Street) txt.Rtf = txt.Rtf.Replace("<%City%>", clientrow.City) txt.Rtf = txt.Rtf.Replace("<%State%>", clientrow.State) txt.Rtf = txt.Rtf.Replace("<%Zip%>", clientrow.Zip) txt.Rtf = txt.Rtf.Replace("<%PhoneH%>", clientrow.PhoneH) txt.Rtf = txt.Rtf.Replace("<%PhoneW%>", clientrow.PhoneW) txt.Rtf = txt.Rtf.Replace("<%Date%>", DateTime.Today.ToShortDateString) Try PDoc.PrinterSettings = printDlg.PrinterSettings PDoc.Print() prow.Printed = True adapterPrintJobs.Update(prow) Catch ex As Exception End Try End If Next prow ds.PrintJobs.Clear() Catch ex As Exception MessageBox.Show(ex.Message, "Print", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub And in frmEmail i've the Following Sub Public Sub SendEmails() try adapterLettersInSchedules.Fill(ds.LettersInSchedules) adapterLetters.Fill(ds.Letters) adapterClients.Fill(ds.Clients) adapterEmailJobs.GetEmailJobsDueToday(ds.EmailJobs, False, Today) Dim ls_string As String For Each prow As MyDataSet.EmailJobsRow In ds.EmailJobs Dim lisrow As MyDataSet.LettersInSchedulesRow = ds.LettersInSchedules.FindByID(prow.LetterInScheduleID) If lisrow.Isemail = True Then Dim clientrow As MyDataSet.ClientsRow = ds.Clients.FindByClientID(prow.ClientID) Dim letterrow As MyDataSet.LettersRow = ds.Letters.FindByID(lisrow.LetterID) txt.Rtf = letterrow.LetterContents ls_string = RTF2HTML(txt.Rtf) ls_string = Mid(ls_string, 1, Len(ls_string) - 176) If ls_string = "" Then Throw New Exception("Rtf To HTML Conversion Failed") Label1.SuspendLayout() Label1.Refresh() Label1.Text = "Sending Email" If SendEmail(clientrow.Email, ls_string, letterrow.EmailSubject) Then Try prow.Emailed = True adapterEmailJobs.Update(prow) Catch ex As Exception End Try Else prow.Emailed = False adapterEmailJobs.Update(prow) End If End If Next prow Catch ex As Exception MessageBox.Show(ex.Message, "Email", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub I'm running this two subs using two different Threads. Public th As New Thread(New ThreadStart(AddressOf StartFirstPrint)) Public th4 As New Thread(New ThreadStart(AddressOf sendFirstEmail)) Here is the code of StartFirstPrint and sendFirstEmail Public Sub StartFirstPrint() Do While thCont Try Dim frm As New frmPrint() 'frm.MdiParent = Me frm.StartPrinting() Catch ex As Exception End Try Loop End Sub Public Sub sendFirstEmail() Do While thCont Try Dim frmSNDEmail As New frmEmail frmSNDEmail.SendEmails() Catch ex As Exception End Try Loop End Sub the thCont is a public boolean variable that specifies when to shop those threads. Most Of the time this works very well. But some times it gives errors Like the following image I don't know why is this occurring. Please help me.

    Read the article

  • Overriding Debian default groups from LDAP

    - by Ex-Parrot
    This is a thing that has always bothered me: how am I best to handle Debian standard groups for LDAP users? Debian has a number of groups defined by default, e.g. plugdev, audio, cdrom and so on. These control access in standard Debian installs. When I want a user from LDAP to be a member of the `audio' group on all machines they log in to, I've tried a few different things: Adding them to the local group on the machine (this works but is hard to maintain) Creating a group in LDAP with the same name and a different GID then adding the user to that group (breaks reverse / forward GID mapping, doesn't seem to work) Creating a group in LDAP with the same name and same GID and adding the user to that group (doesn't seem to work at all, things don't see the LDAP group members) Creating a group in LDAP with the same name and same GID then removing the local group (this works but upsets Debian's maintenance scripts during upgrades that check for local system sanity) What's the best practice for this scenario?

    Read the article

  • Using JDialog with Tabbed Pane to draw different pictures [migrated]

    - by Bryam Ulloa
    I am using NetBeans, and I have a class that extends to JDialog, inside that Dialog box I have created a Tabbed Pane. The Tabbed Pane contains 6 different tabs, with 6 different panels of course. What I want to do is when I click on the different tabs, a diagram is supposed to be drawn with the paint method. My question is how can I draw on the different panels with just one paint method in another class being called from the Dialog class? Here is my code for the Dialog class: package GUI; public class NewJDialog extends javax.swing.JDialog{ /** * Creates new form NewJDialog */ public NewJDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("FCFS", jPanel1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SSTF", jPanel2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK", jPanel3); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("LOOK C", jPanel4); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN", jPanel5); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 466, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 242, Short.MAX_VALUE) ); jTabbedPane1.addTab("SCAN C", jPanel6); getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); jLabel1.setText("Distancia:"); jLabel2.setText("___________"); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addContainerGap(331, Short.MAX_VALUE)) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addContainerGap(15, Short.MAX_VALUE)) ); getContentPane().add(jPanel7, java.awt.BorderLayout.PAGE_START); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration } This is another class that I have created for the paint method: package GUI; import java.awt.Graphics; import javax.swing.JPanel; /** * * @author TOSHIBA */ public class Lienzo { private int width = 5; private int height = 5; private int y = 5; private int x = 0; private int x1 = 0; public Graphics Draw(Graphics g, int[] pistas) { //Im not sure if this is the correct way to do it //The diagram gets drawn according to values from an array //The array is not always the same thats why I used the different Panels for (int i = 0; i < pistas.length; i++) { x = pistas[i]; x1 = pistas[i + 1]; g.drawOval(x, y, width, height); g.drawString(Integer.toString(x), x, y); g.drawLine(x, y, x1, y); } return g; } } I hope you guys understand what I am trying to do with my program.

    Read the article

  • Convert Excel File 'xls' to CSV, CAUTION: Bumps Ahead

    - by faizanahmad
    The task was to provide users with an interface where they can upload the 'csv' files, these files were to be processed and loaded to Database by a Console application. The code in Console application could not handle the 'xls' files so we thought, OK, lets convert 'xls' to 'csv' in the code, Seemed like fun. The idea was to convert it right after uploading within 'csv' file. As Microsoft does not recommend using the  Excel objects in ASP.NET, we decided to use the Jet engine to open xls. (Ace driver is used for xlsx) The code was pretty straight, can be found on following links: http://www.c-sharpcorner.com/uploadfile/yuanwang200409/102242008174401pm/1.aspx http://www.devasp.net/net/articles/display/141.html FIRST BUMP 'OleDbException (0x80004005): Unspecified error' ( Impersonation ): The ablove code ran fine in my test web site and test console application, but it gave an 'OleDbException (0x80004005): Unspecified error' in main web site, turns out imperonation was set to True and as soon as I changed it to False, it did work. on My XP box, web site was running under user                   'ASPNET'  with imperosnation set to FALSE                   'IUSR_*' i.e IIS guest user with impersonation set to TRUE The weired part was that both users had same rights on the folders I was saving files to and on Excel app in DCOM Config.  We decided to give it a try on Windows Server 2003 with web site set to windows authentication ( impersonation = true ) and yes it did work. SECOND BUMP 'External table not in correct format': I got this error with some files and it appeared that the file from client has some metadata issues  ( when I opened the file in Excel and try to save it ,excel  would give me this error saying File can not be saved in current format ) and the error was caused by that. Some people were able to reslove the error by using "Extended Properties=HTML Import;" in connection string. But it did not work for me. We decided to detour from here and use Excel object :( as we had no control on client setting the meta deta of Excel files. Before third bump there were a ouple of small thingies like 'Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005' Fix can be found at http://blog.crowe.co.nz/archive/2006/03/02/589.aspx THIRD BUMP ( Could not get rid of the EXCEL process  ):  I has all the code in place to 'Quiet' the excel, but, it just did not work. work around was done to Kill the process as we knew no other application on server was using EXCEL.  The normal steps to quite the excel application worked just fine in console application though.   FOURTH BUMP: Code worked with one file 1 on my machine and with the other file 2 code will break. and the same code will work perfectly fine with file 2 on some other machine . We moved it to QA  ( Windows Server 2003 )and worked with every file just perfect. But , then there was another problem: one user can upload it and second cant, permissions on folder and DCOM Conifg checked. Another Detour: Uplooad the xls as it is and convert in Console application.   Lesson Learnt:  If its 'xlsx' use 'ACE Driver' or read xml within excel as recommneded by MS. If xls and you know its always going to be properly formatted  'jet Engine'  Code: Imports Microsoft.Office.Interop Private Function ConvertFile(ByVal SourceFolder As String, ByVal FileName As String, ByVal FileExtension As String)As Boolean     Dim appExcel As New Excel.Application     Dim workBooks As Excel.Workbooks = appExcel.Workbooks     Dim objWorkbook As Excel.Workbook      Try                   objWorkbook = workBooks.Open(CompleteFilePath )                            objWorkbook.SaveAs(Filename:=CObj(SourceFolder & FileName & ".csv"), FileFormat:=Excel.XlFileFormat.xlCSV)       Catch ex As Exception         GenerateAlert(ex.Message().Replace("'", "") & " Error Converting File to CSV.")         LogError(ex )         Return False      Finally                      If Not(objWorkbook is Nothing) then               objWorkbook.Close(SaveChanges:=CObj(False))           End If           ReleaseObj(objWorkbook)                                      ReleaseObj(workBooks)           appExcel.Quit()           ReleaseObj(appExcel)                                 Dim proc As System.Diagnostics.Process           For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")               proc.Kill()           Next         DeleteSourceFile(SourceFolder & FileName & FileExtension)     End Try  Return True  End Function   Private Sub ReleaseObj(ByVal o As Object)     Try      System.Runtime.InteropServices.Marshal.ReleaseComObject(o)   Catch ex As Exception           LogError(ex )   Finally      o = Nothing    End Try End Sub     Protected Sub DeleteSourceFile(Byval CompleteFilePath As string)         Try             Dim MyFile As FileInfo = New FileInfo(CompleteFilePath)             If  MyFile.Exists Then                 File.Delete(CompleteFilePath)             Else              Throw New FileNotFoundException()             End If         Catch ex As Exception             GenerateAlert( " Source File could not be deleted.")              LogError(ex)         End Try     End Sub  The code to kill the process ( Avoid it if you can ): Dim proc As System.Diagnostics.Process For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")     proc.Kill() Next

    Read the article

  • Why does setting a geometry shader cause my sprites to vanish?

    - by ChaosDev
    My application has multiple screens with different tasks. Once I set a geometry shader to the device context for my custom terrain, it works and I get the desired results. But then when I get back to the main menu, all sprites and text disappear. These sprites don't dissappear when I use pixel and vertex shaders. The sprites are being drawn through D3D11, of course, with specified view and projection matrices as well an input layout, vertex, and pixel shader. I'm trying DeviceContext->ClearState() but it does not help. Any ideas? void gGeometry::DrawIndexedWithCustomEffect(gVertexShader*vs,gPixelShader* ps,gGeometryShader* gs=nullptr) { unsigned int offset = 0; auto context = mp_D3D->mp_Context; //set topology context->IASetPrimitiveTopology(m_Topology); //set input layout context->IASetInputLayout(mp_inputLayout); //set vertex and index buffers context->IASetVertexBuffers(0,1,&mp_VertexBuffer->mp_Buffer,&m_VertexStride,&offset); context->IASetIndexBuffer(mp_IndexBuffer->mp_Buffer,mp_IndexBuffer->m_DXGIFormat,0); //send constant buffers to shaders context->VSSetConstantBuffers(0,vs->m_CBufferCount,vs->m_CRawBuffers.data()); context->PSSetConstantBuffers(0,ps->m_CBufferCount,ps->m_CRawBuffers.data()); if(gs!=nullptr) { context->GSSetConstantBuffers(0,gs->m_CBufferCount,gs->m_CRawBuffers.data()); context->GSSetShader(gs->mp_D3DGeomShader,0,0);//after this call all sprites disappear } //set shaders context->VSSetShader( vs->mp_D3DVertexShader, 0, 0 ); context->PSSetShader( ps->mp_D3DPixelShader, 0, 0 ); //draw context->DrawIndexed(m_indexCount,0,0); } //sprites void gSpriteDrawer::Draw(gTexture2D* texture,const RECT& dest,const RECT& source, const Matrix& spriteMatrix,const float& rotation,Vector2d& position,const Vector2d& origin,const Color& color) { VertexPositionColorTexture* verticesPtr; D3D11_MAPPED_SUBRESOURCE mappedResource; unsigned int TriangleVertexStride = sizeof(VertexPositionColorTexture); unsigned int offset = 0; float halfWidth = ( float )dest.right / 2.0f; float halfHeight = ( float )dest.bottom / 2.0f; float z = 0.1f; int w = texture->Width(); int h = texture->Height(); float tu = (float)source.right/(w); float tv = (float)source.bottom/(h); float hu = (float)source.left/(w); float hv = (float)source.top/(h); Vector2d t0 = Vector2d( hu+tu, hv); Vector2d t1 = Vector2d( hu+tu, hv+tv); Vector2d t2 = Vector2d( hu, hv+tv); Vector2d t3 = Vector2d( hu, hv+tv); Vector2d t4 = Vector2d( hu, hv); Vector2d t5 = Vector2d( hu+tu, hv); float ex=(dest.right/2)+(origin.x); float ey=(dest.bottom/2)+(origin.y); Vector4d v4Color = Vector4d(color.r,color.g,color.b,color.a); VertexPositionColorTexture vertices[] = { { Vector3d( dest.right-ex, -ey, z),v4Color, t0}, { Vector3d( dest.right-ex, dest.bottom-ey , z),v4Color, t1}, { Vector3d( -ex, dest.bottom-ey , z),v4Color, t2}, { Vector3d( -ex, dest.bottom-ey , z),v4Color, t3}, { Vector3d( -ex, -ey , z),v4Color, t4}, { Vector3d( dest.right-ex, -ey , z),v4Color, t5}, }; auto mp_context = mp_D3D->mp_Context; // Lock the vertex buffer so it can be written to. mp_context->Map(mp_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); // Get a pointer to the data in the vertex buffer. verticesPtr = (VertexPositionColorTexture*)mappedResource.pData; // Copy the data into the vertex buffer. memcpy(verticesPtr, (void*)vertices, (sizeof(VertexPositionColorTexture) * 6)); // Unlock the vertex buffer. mp_context->Unmap(mp_vertexBuffer, 0); //set vertex shader mp_context->IASetVertexBuffers( 0, 1, &mp_vertexBuffer, &TriangleVertexStride, &offset); //set texture mp_context->PSSetShaderResources( 0, 1, &texture->mp_SRV); //set matrix to shader mp_context->UpdateSubresource(mp_matrixBuffer, 0, 0, &spriteMatrix, 0, 0 ); mp_context->VSSetConstantBuffers( 0, 1, &mp_matrixBuffer); //draw sprite mp_context->Draw( 6, 0 ); }

    Read the article

  • Netbeans Java SE GUI Builder: private initComponents() problem

    - by maSnun
    When I build a GUI for my Java SE app with Netbeans GUI builder, it puts all the codes in the initComponents() method which is private. I could not change it to public. So, all the components are accessible only to the class containing the UI. I want to access those components from another class so that I can write custom event handlers and everything. Most importantly I want to separate my GUI code and non-GUI from each other. I can copy paste the GUI code and later make them public by hand to achieve what I want. But thats a pain. I have to handcraft a portion whenever I need to re-design the UI. What I tried to do: I used the variable identifier to make the text box public. Now how can I access the text box from the Main class? I think I need the component generated in a public method as well. I am new to Java. Any helps? Here's the sample classes: The UI (uiFrame.java) /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * uiFrame.java * * Created on Jun 3, 2010, 9:33:15 PM */ package barcode; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import net.sourceforge.barbecue.output.OutputException; /** * * @author masnun */ public class uiFrame extends javax.swing.JFrame { /** Creates new form uiFrame */ public uiFrame() { try { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } } finally { } initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { label1 = new javax.swing.JLabel(); textBox = new javax.swing.JTextField(); saveButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); label1.setFont(label1.getFont().deriveFont(label1.getFont().getStyle() | java.awt.Font.BOLD, 13)); label1.setText("Type a text:"); label1.setName("label1"); // NOI18N saveButton.setText("Save"); saveButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { saveButtonMousePressed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(textBox, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(72, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(154, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(144, 144, 144)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(140, Short.MAX_VALUE) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(127, 127, 127)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(saveButton) .addContainerGap(193, Short.MAX_VALUE)) ); pack(); }// </editor-fold> @SuppressWarnings("static-access") private void saveButtonMousePressed(java.awt.event.MouseEvent evt) { JFileChooser file = new JFileChooser(); file.showSaveDialog(null); String data = file.getSelectedFile().getAbsolutePath(); String text = textBox.getText(); BarcodeGenerator barcodeFactory = new BarcodeGenerator(); try { barcodeFactory.generateBarcode(text, data); } catch (OutputException ex) { Logger.getLogger(uiFrame.class.getName()).log(Level.SEVERE, null, ex); } } /** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JLabel label1; private javax.swing.JButton saveButton; public javax.swing.JTextField textBox; // End of variables declaration } The Main Class (Main.java) package barcode; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame ui = new uiFrame(); ui.pack(); ui.show(); } }

    Read the article

  • Using System.DateTime in a C# Lambda expression gives an exception

    - by Samantha J
    I tried to implement a suggestion that came up in another question: Stackoverflow question Snippet here: public static class StatusExtensions { public static IHtmlString StatusBox<TModel>( this HtmlHelper<TModel> helper, Expression<Func<TModel, RowInfo>> ex ) { var createdEx = Expression.Lambda<Func<TModel, DateTime>>( Expression.Property(ex.Body, "Created"), ex.Parameters ); var modifiedEx = Expression.Lambda<Func<TModel, DateTime>>( Expression.Property(ex.Body, "Modified"), ex.Parameters ); var a = "a" + helper.HiddenFor(createdEx) + helper.HiddenFor(modifiedEx); return new HtmlString( "Some things here ..." + helper.HiddenFor(createdEx) + helper.HiddenFor(modifiedEx) ); } } When implemented I am getting the following exception which I don't really understand. The exception points to the line starting with "var createdEx =" System.ArgumentException was unhandled by user code Message=Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.DateTime' Source=System.Core StackTrace: Can anyone help me out and suggest what I could do to resolve the exception?

    Read the article

  • Can this loop take out 100% CPU?

    - by Nitesh Panchal
    Hello, I created a chat application and seems to work just fine except that it takes up 100% cpu. Can this loop take out 100% Cpu? If yes, then what do i do to overcome it? @Override public void run(){ try { _objServerSocket = new ServerSocket(17001, 500); while (true) { try { initializeConnection(); addNewChatClient(); Thread.sleep(1000); } catch (Exception ex) { } } } catch (IOException ex) { System.out.println(ex.getCause() + "\n"+ ex.getMessage() + "\n" + ex.getStackTrace()); } } Thanks in advance :)

    Read the article

  • Hosting the Razor Engine for Templating in Non-Web Applications

    - by Rick Strahl
    Microsoft’s new Razor HTML Rendering Engine that is currently shipping with ASP.NET MVC previews can be used outside of ASP.NET. Razor is an alternative view engine that can be used instead of the ASP.NET Page engine that currently works with ASP.NET WebForms and MVC. It provides a simpler and more readable markup syntax and is much more light weight in terms of functionality than the full blown WebForms Page engine, focusing only on features that are more along the lines of a pure view engine (or classic ASP!) with focus on expression and code rendering rather than a complex control/object model. Like the Page engine though, the parser understands .NET code syntax which can be embedded into templates, and behind the scenes the engine compiles markup and script code into an executing piece of .NET code in an assembly. Although it ships as part of the ASP.NET MVC and WebMatrix the Razor Engine itself is not directly dependent on ASP.NET or IIS or HTTP in any way. And although there are some markup and rendering features that are optimized for HTML based output generation, Razor is essentially a free standing template engine. And what’s really nice is that unlike the ASP.NET Runtime, Razor is fairly easy to host inside of your own non-Web applications to provide templating functionality. Templating in non-Web Applications? Yes please! So why might you host a template engine in your non-Web application? Template rendering is useful in many places and I have a number of applications that make heavy use of it. One of my applications – West Wind Html Help Builder - exclusively uses template based rendering to merge user supplied help text content into customizable and executable HTML markup templates that provide HTML output for CHM style HTML Help. This is an older product and it’s not actually using .NET at the moment – and this is one reason I’m looking at Razor for script hosting at the moment. For a few .NET applications though I’ve actually used the ASP.NET Runtime hosting to provide templating and mail merge style functionality and while that works reasonably well it’s a very heavy handed approach. It’s very resource intensive and has potential issues with versioning in various different versions of .NET. The generic implementation I created in the article above requires a lot of fix up to mimic an HTTP request in a non-HTTP environment and there are a lot of little things that have to happen to ensure that the ASP.NET runtime works properly most of it having nothing to do with the templating aspect but just satisfying ASP.NET’s requirements. The Razor Engine on the other hand is fairly light weight and completely decoupled from the ASP.NET runtime and the HTTP processing. Rather it’s a pure template engine whose sole purpose is to render text templates. Hosting this engine in your own applications can be accomplished with a reasonable amount of code (actually just a few lines with the tools I’m about to describe) and without having to fake HTTP requests. It’s also much lighter on resource usage and you can easily attach custom properties to your base template implementation to easily pass context from the parent application into templates all of which was rather complicated with ASP.NET runtime hosting. Installing the Razor Template Engine You can get Razor as part of the MVC 3 (RC and later) or Web Matrix. Both are available as downloadable components from the Web Platform Installer Version 3.0 (!important – V2 doesn’t show these components). If you already have that version of the WPI installed just fire it up. You can get the latest version of the Web Platform Installer from here: http://www.microsoft.com/web/gallery/install.aspx Once the platform Installer 3.0 is installed install either MVC 3 or ASP.NET Web Pages. Once installed you’ll find a System.Web.Razor assembly in C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.Razor.dll which you can add as a reference to your project. Creating a Wrapper The basic Razor Hosting API is pretty simple and you can host Razor with a (large-ish) handful of lines of code. I’ll show the basics of it later in this article. However, if you want to customize the rendering and handle assembly and namespace includes for the markup as well as deal with text and file inputs as well as forcing Razor to run in a separate AppDomain so you can unload the code-generated assemblies and deal with assembly caching for re-used templates little more work is required to create something that is more easily reusable. For this reason I created a Razor Hosting wrapper project that combines a bunch of this functionality into an easy to use hosting class, a hosting factory that can load the engine in a separate AppDomain and a couple of hosting containers that provided folder based and string based caching for templates for an easily embeddable and reusable engine with easy to use syntax. If you just want the code and play with the samples and source go grab the latest code from the Subversion Repository at: http://www.west-wind.com:8080/svn/articles/trunk/RazorHosting/ or a snapshot from: http://www.west-wind.com/files/tools/RazorHosting.zip Getting Started Before I get into how hosting with Razor works, let’s take a look at how you can get up and running quickly with the wrapper classes provided. It only takes a few lines of code. The easiest way to use these Razor Hosting Wrappers is to use one of the two HostContainers provided. One is for hosting Razor scripts in a directory and rendering them as relative paths from these script files on disk. The other HostContainer serves razor scripts from string templates… Let’s start with a very simple template that displays some simple expressions, some code blocks and demonstrates rendering some data from contextual data that you pass to the template in the form of a ‘context’. Here’s a simple Razor template: @using System.Reflection Hello @Context.FirstName! Your entry was entered on: @Context.Entered @{ // Code block: Update the host Windows Form passed in through the context Context.WinForm.Text = "Hello World from Razor at " + DateTime.Now.ToString(); } AppDomain Id: @AppDomain.CurrentDomain.FriendlyName Assembly: @Assembly.GetExecutingAssembly().FullName Code based output: @{ // Write output with Response object from code string output = string.Empty; for (int i = 0; i < 10; i++) { output += i.ToString() + " "; } Response.Write(output); } Pretty easy to see what’s going on here. The only unusual thing in this code is the Context object which is an arbitrary object I’m passing from the host to the template by way of the template base class. I’m also displaying the current AppDomain and the executing Assembly name so you can see how compiling and running a template actually loads up new assemblies. Also note that as part of my context I’m passing a reference to the current Windows Form down to the template and changing the title from within the script. It’s a silly example, but it demonstrates two-way communication between host and template and back which can be very powerful. The easiest way to quickly render this template is to use the RazorEngine<TTemplateBase> class. The generic parameter specifies a template base class type that is used by Razor internally to generate the class it generates from a template. The default implementation provided in my RazorHosting wrapper is RazorTemplateBase. Here’s a simple one that renders from a string and outputs a string: var engine = new RazorEngine<RazorTemplateBase>(); // we can pass any object as context - here create a custom context var context = new CustomContext() { WinForm = this, FirstName = "Rick", Entered = DateTime.Now.AddDays(-10) }; string output = engine.RenderTemplate(this.txtSource.Text new string[] { "System.Windows.Forms.dll" }, context); if (output == null) this.txtResult.Text = "*** ERROR:\r\n" + engine.ErrorMessage; else this.txtResult.Text = output; Simple enough. This code renders a template from a string input and returns a result back as a string. It  creates a custom context and passes that to the template which can then access the Context’s properties. Note that anything passed as ‘context’ must be serializable (or MarshalByRefObject) – otherwise you get an exception when passing the reference over AppDomain boundaries (discussed later). Passing a context is optional, but is a key feature in being able to share data between the host application and the template. Note that we use the Context object to access FirstName, Entered and even the host Windows Form object which is used in the template to change the Window caption from within the script! In the code above all the work happens in the RenderTemplate method which provide a variety of overloads to read and write to and from strings, files and TextReaders/Writers. Here’s another example that renders from a file input using a TextReader: using (reader = new StreamReader("templates\\simple.csHtml", true)) { result = host.RenderTemplate(reader, new string[] { "System.Windows.Forms.dll" }, this.CustomContext); } RenderTemplate() is fairly high level and it handles loading of the runtime, compiling into an assembly and rendering of the template. If you want more control you can use the lower level methods to control each step of the way which is important for the HostContainers I’ll discuss later. Basically for those scenarios you want to separate out loading of the engine, compiling into an assembly and then rendering the template from the assembly. Why? So we can keep assemblies cached. In the code above a new assembly is created for each template rendered which is inefficient and uses up resources. Depending on the size of your templates and how often you fire them you can chew through memory very quickly. This slighter lower level approach is only a couple of extra steps: // we can pass any object as context - here create a custom context var context = new CustomContext() { WinForm = this, FirstName = "Rick", Entered = DateTime.Now.AddDays(-10) }; var engine = new RazorEngine<RazorTemplateBase>(); string assId = null; using (StringReader reader = new StringReader(this.txtSource.Text)) { assId = engine.ParseAndCompileTemplate(new string[] { "System.Windows.Forms.dll" }, reader); } string output = engine.RenderTemplateFromAssembly(assId, context); if (output == null) this.txtResult.Text = "*** ERROR:\r\n" + engine.ErrorMessage; else this.txtResult.Text = output; The difference here is that you can capture the assembly – or rather an Id to it – and potentially hold on to it to render again later assuming the template hasn’t changed. The HostContainers take advantage of this feature to cache the assemblies based on certain criteria like a filename and file time step or a string hash that if not change indicate that an assembly can be reused. Note that ParseAndCompileTemplate returns an assembly Id rather than the assembly itself. This is done so that that the assembly always stays in the host’s AppDomain and is not passed across AppDomain boundaries which would cause load failures. We’ll talk more about this in a minute but for now just realize that assemblies references are stored in a list and are accessible by this ID to allow locating and re-executing of the assembly based on that id. Reuse of the assembly avoids recompilation overhead and creation of yet another assembly that loads into the current AppDomain. You can play around with several different versions of the above code in the main sample form:   Using Hosting Containers for more Control and Caching The above examples simply render templates into assemblies each and every time they are executed. While this works and is even reasonably fast, it’s not terribly efficient. If you render templates more than once it would be nice if you could cache the generated assemblies for example to avoid re-compiling and creating of a new assembly each time. Additionally it would be nice to load template assemblies into a separate AppDomain optionally to be able to be able to unload assembli es and also to protect your host application from scripting attacks with malicious template code. Hosting containers provide also provide a wrapper around the RazorEngine<T> instance, a factory (which allows creation in separate AppDomains) and an easy way to start and stop the container ‘runtime’. The Razor Hosting samples provide two hosting containers: RazorFolderHostContainer and StringHostContainer. The folder host provides a simple runtime environment for a folder structure similar in the way that the ASP.NET runtime handles a virtual directory as it’s ‘application' root. Templates are loaded from disk in relative paths and the resulting assemblies are cached unless the template on disk is changed. The string host also caches templates based on string hashes – if the same string is passed a second time a cached version of the assembly is used. Here’s how HostContainers work. I’ll use the FolderHostContainer because it’s likely the most common way you’d use templates – from disk based templates that can be easily edited and maintained on disk. The first step is to create an instance of it and keep it around somewhere (in the example it’s attached as a property to the Form): RazorFolderHostContainer Host = new RazorFolderHostContainer(); public RazorFolderHostForm() { InitializeComponent(); // The base path for templates - templates are rendered with relative paths // based on this path. Host.TemplatePath = Path.Combine(Environment.CurrentDirectory, TemplateBaseFolder); // Add any assemblies you want reference in your templates Host.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Start up the host container Host.Start(); } Next anytime you want to render a template you can use simple code like this: private void RenderTemplate(string fileName) { // Pass the template path via the Context var relativePath = Utilities.GetRelativePath(fileName, Host.TemplatePath); if (!Host.RenderTemplate(relativePath, this.Context, Host.RenderingOutputFile)) { MessageBox.Show("Error: " + Host.ErrorMessage); return; } this.webBrowser1.Navigate("file://" + Host.RenderingOutputFile); } You can also render the output to a string instead of to a file: string result = Host.RenderTemplateToString(relativePath,context); Finally if you want to release the engine and shut down the hosting AppDomain you can simply do: Host.Stop(); Stopping the AppDomain and restarting it (ie. calling Stop(); followed by Start()) is also a nice way to release all resources in the AppDomain. The FolderBased domain also supports partial Rendering based on root path based relative paths with the same caching characteristics as the main templates. From within a template you can call out to a partial like this: @RenderPartial(@"partials\PartialRendering.cshtml", Context) where partials\PartialRendering.cshtml is a relative to the template root folder. The folder host example lets you load up templates from disk and display the result in a Web Browser control which demonstrates using Razor HTML output from templates that contain HTML syntax which happens to me my target scenario for Html Help Builder.   The Razor Engine Wrapper Project The project I created to wrap Razor hosting has a fair bit of code and a number of classes associated with it. Most of the components are internally used and as you can see using the final RazorEngine<T> and HostContainer classes is pretty easy. The classes are extensible and I suspect developers will want to build more customized host containers for their applications. Host containers are the key to wrapping up all functionality – Engine, BaseTemplate, AppDomain Hosting, Caching etc in a logical piece that is ready to be plugged into an application. When looking at the code there are a couple of core features provided: Core Razor Engine Hosting This is the core Razor hosting which provides the basics of loading a template, compiling it into an assembly and executing it. This is fairly straightforward, but without a host container that can cache assemblies based on some criteria templates are recompiled and re-created each time which is inefficient (although pretty fast). The base engine wrapper implementation also supports hosting the Razor runtime in a separate AppDomain for security and the ability to unload it on demand. Host Containers The engine hosting itself doesn’t provide any sort of ‘runtime’ service like picking up files from disk, caching assemblies and so forth. So my implementation provides two HostContainers: RazorFolderHostContainer and RazorStringHostContainer. The FolderHost works off a base directory and loads templates based on relative paths (sort of like the ASP.NET runtime does off a virtual). The HostContainers also deal with caching of template assemblies – for the folder host the file date is tracked and checked for updates and unless the template is changed a cached assembly is reused. The StringHostContainer similiarily checks string hashes to figure out whether a particular string template was previously compiled and executed. The HostContainers also act as a simple startup environment and a single reference to easily store and reuse in an application. TemplateBase Classes The template base classes are the base classes that from which the Razor engine generates .NET code. A template is parsed into a class with an Execute() method and the class is based on this template type you can specify. RazorEngine<TBaseTemplate> can receive this type and the HostContainers default to specific templates in their base implementations. Template classes are customizable to allow you to create templates that provide application specific features and interaction from the template to your host application. How does the RazorEngine wrapper work? You can browse the source code in the links above or in the repository or download the source, but I’ll highlight some key features here. Here’s part of the RazorEngine implementation that can be used to host the runtime and that demonstrates the key code required to host the Razor runtime. The RazorEngine class is implemented as a generic class to reflect the Template base class type: public class RazorEngine<TBaseTemplateType> : MarshalByRefObject where TBaseTemplateType : RazorTemplateBase The generic type is used to internally provide easier access to the template type and assignments on it as part of the template processing. The class also inherits MarshalByRefObject to allow execution over AppDomain boundaries – something that all the classes discussed here need to do since there is much interaction between the host and the template. The first two key methods deal with creating a template assembly: /// <summary> /// Creates an instance of the RazorHost with various options applied. /// Applies basic namespace imports and the name of the class to generate /// </summary> /// <param name="generatedNamespace"></param> /// <param name="generatedClass"></param> /// <returns></returns> protected RazorTemplateEngine CreateHost(string generatedNamespace, string generatedClass) { Type baseClassType = typeof(TBaseTemplateType); RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage()); host.DefaultBaseClass = baseClassType.FullName; host.DefaultClassName = generatedClass; host.DefaultNamespace = generatedNamespace; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Text"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Linq"); host.NamespaceImports.Add("System.IO"); return new RazorTemplateEngine(host); } /// <summary> /// Parses and compiles a markup template into an assembly and returns /// an assembly name. The name is an ID that can be passed to /// ExecuteTemplateByAssembly which picks up a cached instance of the /// loaded assembly. /// /// </summary> /// <param name="namespaceOfGeneratedClass">The namespace of the class to generate from the template</param> /// <param name="generatedClassName">The name of the class to generate from the template</param> /// <param name="ReferencedAssemblies">Any referenced assemblies by dll name only. Assemblies must be in execution path of host or in GAC.</param> /// <param name="templateSourceReader">Textreader that loads the template</param> /// <remarks> /// The actual assembly isn't returned here to allow for cross-AppDomain /// operation. If the assembly was returned it would fail for cross-AppDomain /// calls. /// </remarks> /// <returns>An assembly Id. The Assembly is cached in memory and can be used with RenderFromAssembly.</returns> public string ParseAndCompileTemplate( string namespaceOfGeneratedClass, string generatedClassName, string[] ReferencedAssemblies, TextReader templateSourceReader) { RazorTemplateEngine engine = CreateHost(namespaceOfGeneratedClass, generatedClassName); // Generate the template class as CodeDom GeneratorResults razorResults = engine.GenerateCode(templateSourceReader); // Create code from the codeDom and compile CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions options = new CodeGeneratorOptions(); // Capture Code Generated as a string for error info // and debugging LastGeneratedCode = null; using (StringWriter writer = new StringWriter()) { codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options); LastGeneratedCode = writer.ToString(); } CompilerParameters compilerParameters = new CompilerParameters(ReferencedAssemblies); // Standard Assembly References compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); // dynamic support! // Also add the current assembly so RazorTemplateBase is available compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8)); compilerParameters.GenerateInMemory = Configuration.CompileToMemory; if (!Configuration.CompileToMemory) compilerParameters.OutputAssembly = Path.Combine(Configuration.TempAssemblyPath, "_" + Guid.NewGuid().ToString("n") + ".dll"); CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode); if (compilerResults.Errors.Count > 0) { var compileErrors = new StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors) compileErrors.Append(String.Format(Resources.LineX0TColX1TErrorX2RN, compileError.Line, compileError.Column, compileError.ErrorText)); this.SetError(compileErrors.ToString() + "\r\n" + LastGeneratedCode); return null; } AssemblyCache.Add(compilerResults.CompiledAssembly.FullName, compilerResults.CompiledAssembly); return compilerResults.CompiledAssembly.FullName; } Think of the internal CreateHost() method as setting up the assembly generated from each template. Each template compiles into a separate assembly. It sets up namespaces, and assembly references, the base class used and the name and namespace for the generated class. ParseAndCompileTemplate() then calls the CreateHost() method to receive the template engine generator which effectively generates a CodeDom from the template – the template is turned into .NET code. The code generated from our earlier example looks something like this: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RazorTest { using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; public class RazorTemplate : RazorHosting.RazorTemplateBase { #line hidden public RazorTemplate() { } public override void Execute() { WriteLiteral("Hello "); Write(Context.FirstName); WriteLiteral("! Your entry was entered on: "); Write(Context.Entered); WriteLiteral("\r\n\r\n"); // Code block: Update the host Windows Form passed in through the context Context.WinForm.Text = "Hello World from Razor at " + DateTime.Now.ToString(); WriteLiteral("\r\nAppDomain Id:\r\n "); Write(AppDomain.CurrentDomain.FriendlyName); WriteLiteral("\r\n \r\nAssembly:\r\n "); Write(Assembly.GetExecutingAssembly().FullName); WriteLiteral("\r\n\r\nCode based output: \r\n"); // Write output with Response object from code string output = string.Empty; for (int i = 0; i < 10; i++) { output += i.ToString() + " "; } } } } Basically the template’s body is turned into code in an Execute method that is called. Internally the template’s Write method is fired to actually generate the output. Note that the class inherits from RazorTemplateBase which is the generic parameter I used to specify the base class when creating an instance in my RazorEngine host: var engine = new RazorEngine<RazorTemplateBase>(); This template class must be provided and it must implement an Execute() and Write() method. Beyond that you can create any class you chose and attach your own properties. My RazorTemplateBase class implementation is very simple: public class RazorTemplateBase : MarshalByRefObject, IDisposable { /// <summary> /// You can pass in a generic context object /// to use in your template code /// </summary> public dynamic Context { get; set; } /// <summary> /// Class that generates output. Currently ultra simple /// with only Response.Write() implementation. /// </summary> public RazorResponse Response { get; set; } public object HostContainer {get; set; } public object Engine { get; set; } public RazorTemplateBase() { Response = new RazorResponse(); } public virtual void Write(object value) { Response.Write(value); } public virtual void WriteLiteral(object value) { Response.Write(value); } /// <summary> /// Razor Parser implements this method /// </summary> public virtual void Execute() {} public virtual void Dispose() { if (Response != null) { Response.Dispose(); Response = null; } } } Razor fills in the Execute method when it generates its subclass and uses the Write() method to output content. As you can see I use a RazorResponse() class here to generate output. This isn’t necessary really, as you could use a StringBuilder or StringWriter() directly, but I prefer using Response object so I can extend the Response behavior as needed. The RazorResponse class is also very simple and merely acts as a wrapper around a TextWriter: public class RazorResponse : IDisposable { /// <summary> /// Internal text writer - default to StringWriter() /// </summary> public TextWriter Writer = new StringWriter(); public virtual void Write(object value) { Writer.Write(value); } public virtual void WriteLine(object value) { Write(value); Write("\r\n"); } public virtual void WriteFormat(string format, params object[] args) { Write(string.Format(format, args)); } public override string ToString() { return Writer.ToString(); } public virtual void Dispose() { Writer.Close(); } public virtual void SetTextWriter(TextWriter writer) { // Close original writer if (Writer != null) Writer.Close(); Writer = writer; } } The Rendering Methods of RazorEngine At this point I’ve talked about the assembly generation logic and the template implementation itself. What’s left is that once you’ve generated the assembly is to execute it. The code to do this is handled in the various RenderXXX methods of the RazorEngine class. Let’s look at the lowest level one of these which is RenderTemplateFromAssembly() and a couple of internal support methods that handle instantiating and invoking of the generated template method: public string RenderTemplateFromAssembly( string assemblyId, string generatedNamespace, string generatedClass, object context, TextWriter outputWriter) { this.SetError(); Assembly generatedAssembly = AssemblyCache[assemblyId]; if (generatedAssembly == null) { this.SetError(Resources.PreviouslyCompiledAssemblyNotFound); return null; } string className = generatedNamespace + "." + generatedClass; Type type; try { type = generatedAssembly.GetType(className); } catch (Exception ex) { this.SetError(Resources.UnableToCreateType + className + ": " + ex.Message); return null; } // Start with empty non-error response (if we use a writer) string result = string.Empty; using(TBaseTemplateType instance = InstantiateTemplateClass(type)) { if (instance == null) return null; if (outputWriter != null) instance.Response.SetTextWriter(outputWriter); if (!InvokeTemplateInstance(instance, context)) return null; // Capture string output if implemented and return // otherwise null is returned if (outputWriter == null) result = instance.Response.ToString(); } return result; } protected virtual TBaseTemplateType InstantiateTemplateClass(Type type) { TBaseTemplateType instance = Activator.CreateInstance(type) as TBaseTemplateType; if (instance == null) { SetError(Resources.CouldnTActivateTypeInstance + type.FullName); return null; } instance.Engine = this; // If a HostContainer was set pass that to the template too instance.HostContainer = this.HostContainer; return instance; } /// <summary> /// Internally executes an instance of the template, /// captures errors on execution and returns true or false /// </summary> /// <param name="instance">An instance of the generated template</param> /// <returns>true or false - check ErrorMessage for errors</returns> protected virtual bool InvokeTemplateInstance(TBaseTemplateType instance, object context) { try { instance.Context = context; instance.Execute(); } catch (Exception ex) { this.SetError(Resources.TemplateExecutionError + ex.Message); return false; } finally { // Must make sure Response is closed instance.Response.Dispose(); } return true; } The RenderTemplateFromAssembly method basically requires the namespace and class to instantate and creates an instance of the class using InstantiateTemplateClass(). It then invokes the method with InvokeTemplateInstance(). These two methods are broken out because they are re-used by various other rendering methods and also to allow subclassing and providing additional configuration tasks to set properties and pass values to templates at execution time. In the default mode instantiation sets the Engine and HostContainer (discussed later) so the template can call back into the template engine, and the context is set when the template method is invoked. The various RenderXXX methods use similar code although they create the assemblies first. If you’re after potentially cashing assemblies the method is the one to call and that’s exactly what the two HostContainer classes do. More on that in a minute, but before we get into HostContainers let’s talk about AppDomain hosting and the like. Running Templates in their own AppDomain With the RazorEngine class above, when a template is parsed into an assembly and executed the assembly is created (in memory or on disk – you can configure that) and cached in the current AppDomain. In .NET once an assembly has been loaded it can never be unloaded so if you’re loading lots of templates and at some time you want to release them there’s no way to do so. If however you load the assemblies in a separate AppDomain that new AppDomain can be unloaded and the assemblies loaded in it with it. In order to host the templates in a separate AppDomain the easiest thing to do is to run the entire RazorEngine in a separate AppDomain. Then all interaction occurs in the other AppDomain and no further changes have to be made. To facilitate this there is a RazorEngineFactory which has methods that can instantiate the RazorHost in a separate AppDomain as well as in the local AppDomain. The host creates the remote instance and then hangs on to it to keep it alive as well as providing methods to shut down the AppDomain and reload the engine. Sounds complicated but cross-AppDomain invocation is actually fairly easy to implement. Here’s some of the relevant code from the RazorEngineFactory class. Like the RazorEngine this class is generic and requires a template base type in the generic class name: public class RazorEngineFactory<TBaseTemplateType> where TBaseTemplateType : RazorTemplateBase Here are the key methods of interest: /// <summary> /// Creates an instance of the RazorHost in a new AppDomain. This /// version creates a static singleton that that is cached and you /// can call UnloadRazorHostInAppDomain to unload it. /// </summary> /// <returns></returns> public static RazorEngine<TBaseTemplateType> CreateRazorHostInAppDomain() { if (Current == null) Current = new RazorEngineFactory<TBaseTemplateType>(); return Current.GetRazorHostInAppDomain(); } public static void UnloadRazorHostInAppDomain() { if (Current != null) Current.UnloadHost(); Current = null; } /// <summary> /// Instance method that creates a RazorHost in a new AppDomain. /// This method requires that you keep the Factory around in /// order to keep the AppDomain alive and be able to unload it. /// </summary> /// <returns></returns> public RazorEngine<TBaseTemplateType> GetRazorHostInAppDomain() { LocalAppDomain = CreateAppDomain(null); if (LocalAppDomain == null) return null; /// Create the instance inside of the new AppDomain /// Note: remote domain uses local EXE's AppBasePath!!! RazorEngine<TBaseTemplateType> host = null; try { Assembly ass = Assembly.GetExecutingAssembly(); string AssemblyPath = ass.Location; host = (RazorEngine<TBaseTemplateType>) LocalAppDomain.CreateInstanceFrom(AssemblyPath, typeof(RazorEngine<TBaseTemplateType>).FullName).Unwrap(); } catch (Exception ex) { ErrorMessage = ex.Message; return null; } return host; } /// <summary> /// Internally creates a new AppDomain in which Razor templates can /// be run. /// </summary> /// <param name="appDomainName"></param> /// <returns></returns> private AppDomain CreateAppDomain(string appDomainName) { if (appDomainName == null) appDomainName = "RazorHost_" + Guid.NewGuid().ToString("n"); AppDomainSetup setup = new AppDomainSetup(); // *** Point at current directory setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain localDomain = AppDomain.CreateDomain(appDomainName, null, setup); return localDomain; } /// <summary> /// Allow unloading of the created AppDomain to release resources /// All internal resources in the AppDomain are released including /// in memory compiled Razor assemblies. /// </summary> public void UnloadHost() { if (this.LocalAppDomain != null) { AppDomain.Unload(this.LocalAppDomain); this.LocalAppDomain = null; } } The static CreateRazorHostInAppDomain() is the key method that startup code usually calls. It uses a Current singleton instance to an instance of itself that is created cross AppDomain and is kept alive because it’s static. GetRazorHostInAppDomain actually creates a cross-AppDomain instance which first creates a new AppDomain and then loads the RazorEngine into it. The remote Proxy instance is returned as a result to the method and can be used the same as a local instance. The code to run with a remote AppDomain is simple: private RazorEngine<RazorTemplateBase> CreateHost() { if (this.Host != null) return this.Host; // Use Static Methods - no error message if host doesn't load this.Host = RazorEngineFactory<RazorTemplateBase>.CreateRazorHostInAppDomain(); if (this.Host == null) { MessageBox.Show("Unable to load Razor Template Host", "Razor Hosting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return this.Host; } This code relies on a local reference of the Host which is kept around for the duration of the app (in this case a form reference). To use this you’d simply do: this.Host = CreateHost(); if (host == null) return; string result = host.RenderTemplate( this.txtSource.Text, new string[] { "System.Windows.Forms.dll", "Westwind.Utilities.dll" }, this.CustomContext); if (result == null) { MessageBox.Show(host.ErrorMessage, "Template Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } this.txtResult.Text = result; Now all templates run in a remote AppDomain and can be unloaded with simple code like this: RazorEngineFactory<RazorTemplateBase>.UnloadRazorHostInAppDomain(); this.Host = null; One Step further – Providing a caching ‘Runtime’ Once we can load templates in a remote AppDomain we can add some additional functionality like assembly caching based on application specific features. One of my typical scenarios is to render templates out of a scripts folder. So all templates live in a folder and they change infrequently. So a Folder based host that can compile these templates once and then only recompile them if something changes would be ideal. Enter host containers which are basically wrappers around the RazorEngine<t> and RazorEngineFactory<t>. They provide additional logic for things like file caching based on changes on disk or string hashes for string based template inputs. The folder host also provides for partial rendering logic through a custom template base implementation. There’s a base implementation in RazorBaseHostContainer, which provides the basics for hosting a RazorEngine, which includes the ability to start and stop the engine, cache assemblies and add references: public abstract class RazorBaseHostContainer<TBaseTemplateType> : MarshalByRefObject where TBaseTemplateType : RazorTemplateBase, new() { public RazorBaseHostContainer() { UseAppDomain = true; GeneratedNamespace = "__RazorHost"; } /// <summary> /// Determines whether the Container hosts Razor /// in a separate AppDomain. Seperate AppDomain /// hosting allows unloading and releasing of /// resources. /// </summary> public bool UseAppDomain { get; set; } /// <summary> /// Base folder location where the AppDomain /// is hosted. By default uses the same folder /// as the host application. /// /// Determines where binary dependencies are /// found for assembly references. /// </summary> public string BaseBinaryFolder { get; set; } /// <summary> /// List of referenced assemblies as string values. /// Must be in GAC or in the current folder of the host app/ /// base BinaryFolder /// </summary> public List<string> ReferencedAssemblies = new List<string>(); /// <summary> /// Name of the generated namespace for template classes /// </summary> public string GeneratedNamespace {get; set; } /// <summary> /// Any error messages /// </summary> public string ErrorMessage { get; set; } /// <summary> /// Cached instance of the Host. Required to keep the /// reference to the host alive for multiple uses. /// </summary> public RazorEngine<TBaseTemplateType> Engine; /// <summary> /// Cached instance of the Host Factory - so we can unload /// the host and its associated AppDomain. /// </summary> protected RazorEngineFactory<TBaseTemplateType> EngineFactory; /// <summary> /// Keep track of each compiled assembly /// and when it was compiled. /// /// Use a hash of the string to identify string /// changes. /// </summary> protected Dictionary<int, CompiledAssemblyItem> LoadedAssemblies = new Dictionary<int, CompiledAssemblyItem>(); /// <summary> /// Call to start the Host running. Follow by a calls to RenderTemplate to /// render individual templates. Call Stop when done. /// </summary> /// <returns>true or false - check ErrorMessage on false </returns> public virtual bool Start() { if (Engine == null) { if (UseAppDomain) Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHostInAppDomain(); else Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHost(); Engine.Configuration.CompileToMemory = true; Engine.HostContainer = this; if (Engine == null) { this.ErrorMessage = EngineFactory.ErrorMessage; return false; } } return true; } /// <summary> /// Stops the Host and releases the host AppDomain and cached /// assemblies. /// </summary> /// <returns>true or false</returns> public bool Stop() { this.LoadedAssemblies.Clear(); RazorEngineFactory<RazorTemplateBase>.UnloadRazorHostInAppDomain(); this.Engine = null; return true; } … } This base class provides most of the mechanics to host the runtime, but no application specific implementation for rendering. There are rendering functions but they just call the engine directly and provide no caching – there’s no context to decide how to cache and reuse templates. The key methods are Start and Stop and their main purpose is to start a new AppDomain (optionally) and shut it down when requested. The RazorFolderHostContainer – Folder Based Runtime Hosting Let’s look at the more application specific RazorFolderHostContainer implementation which is defined like this: public class RazorFolderHostContainer : RazorBaseHostContainer<RazorTemplateFolderHost> Note that a customized RazorTemplateFolderHost class template is used for this implementation that supports partial rendering in form of a RenderPartial() method that’s available to templates. The folder host’s features are: Render templates based on a Template Base Path (a ‘virtual’ if you will) Cache compiled assemblies based on the relative path and file time stamp File changes on templates cause templates to be recompiled into new assemblies Support for partial rendering using base folder relative pathing As shown in the startup examples earlier host containers require some startup code with a HostContainer tied to a persistent property (like a Form property): // The base path for templates - templates are rendered with relative paths // based on this path. HostContainer.TemplatePath = Path.Combine(Environment.CurrentDirectory, TemplateBaseFolder); // Default output rendering disk location HostContainer.RenderingOutputFile = Path.Combine(HostContainer.TemplatePath, "__Preview.htm"); // Add any assemblies you want reference in your templates HostContainer.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Start up the host container HostContainer.Start(); Once that’s done, you can render templates with the host container: // Pass the template path for full filename seleted with OpenFile Dialog // relativepath is: subdir\file.cshtml or file.cshtml or ..\file.cshtml var relativePath = Utilities.GetRelativePath(fileName, HostContainer.TemplatePath); if (!HostContainer.RenderTemplate(relativePath, Context, HostContainer.RenderingOutputFile)) { MessageBox.Show("Error: " + HostContainer.ErrorMessage); return; } webBrowser1.Navigate("file://" + HostContainer.RenderingOutputFile); The most critical task of the RazorFolderHostContainer implementation is to retrieve a template from disk, compile and cache it and then deal with deciding whether subsequent requests need to re-compile the template or simply use a cached version. Internally the GetAssemblyFromFileAndCache() handles this task: /// <summary> /// Internally checks if a cached assembly exists and if it does uses it /// else creates and compiles one. Returns an assembly Id to be /// used with the LoadedAssembly list. /// </summary> /// <param name="relativePath"></param> /// <param name="context"></param> /// <returns></returns> protected virtual CompiledAssemblyItem GetAssemblyFromFileAndCache(string relativePath) { string fileName = Path.Combine(TemplatePath, relativePath).ToLower(); int fileNameHash = fileName.GetHashCode(); if (!File.Exists(fileName)) { this.SetError(Resources.TemplateFileDoesnTExist + fileName); return null; } CompiledAssemblyItem item = null; this.LoadedAssemblies.TryGetValue(fileNameHash, out item); string assemblyId = null; // Check for cached instance if (item != null) { var fileTime = File.GetLastWriteTimeUtc(fileName); if (fileTime <= item.CompileTimeUtc) assemblyId = item.AssemblyId; } else item = new CompiledAssemblyItem(); // No cached instance - create assembly and cache if (assemblyId == null) { string safeClassName = GetSafeClassName(fileName); StreamReader reader = null; try { reader = new StreamReader(fileName, true); } catch (Exception ex) { this.SetError(Resources.ErrorReadingTemplateFile + fileName); return null; } assemblyId = Engine.ParseAndCompileTemplate(this.ReferencedAssemblies.ToArray(), reader); // need to ensure reader is closed if (reader != null) reader.Close(); if (assemblyId == null) { this.SetError(Engine.ErrorMessage); return null; } item.AssemblyId = assemblyId; item.CompileTimeUtc = DateTime.UtcNow; item.FileName = fileName; item.SafeClassName = safeClassName; this.LoadedAssemblies[fileNameHash] = item; } return item; } This code uses a LoadedAssembly dictionary which is comprised of a structure that holds a reference to a compiled assembly, a full filename and file timestamp and an assembly id. LoadedAssemblies (defined on the base class shown earlier) is essentially a cache for compiled assemblies and they are identified by a hash id. In the case of files the hash is a GetHashCode() from the full filename of the template. The template is checked for in the cache and if not found the file stamp is checked. If that’s newer than the cache’s compilation date the template is recompiled otherwise the version in the cache is used. All the core work defers to a RazorEngine<T> instance to ParseAndCompileTemplate(). The three rendering specific methods then are rather simple implementations with just a few lines of code dealing with parameter and return value parsing: /// <summary> /// Renders a template to a TextWriter. Useful to write output into a stream or /// the Response object. Used for partial rendering. /// </summary> /// <param name="relativePath">Relative path to the file in the folder structure</param> /// <param name="context">Optional context object or null</param> /// <param name="writer">The textwriter to write output into</param> /// <returns></returns> public bool RenderTemplate(string relativePath, object context, TextWriter writer) { // Set configuration data that is to be passed to the template (any object) Engine.TemplatePerRequestConfigurationData = new RazorFolderHostTemplateConfiguration() { TemplatePath = Path.Combine(this.TemplatePath, relativePath), TemplateRelativePath = relativePath, }; CompiledAssemblyItem item = GetAssemblyFromFileAndCache(relativePath); if (item == null) { writer.Close(); return false; } try { // String result will be empty as output will be rendered into the // Response object's stream output. However a null result denotes // an error string result = Engine.RenderTemplateFromAssembly(item.AssemblyId, context, writer); if (result == null) { this.SetError(Engine.ErrorMessage); return false; } } catch (Exception ex) { this.SetError(ex.Message); return false; } finally { writer.Close(); } return true; } /// <summary> /// Render a template from a source file on disk to a specified outputfile. /// </summary> /// <param name="relativePath">Relative path off the template root folder. Format: path/filename.cshtml</param> /// <param name="context">Any object that will be available in the template as a dynamic of this.Context</param> /// <param name="outputFile">Optional - output file where output is written to. If not specified the /// RenderingOutputFile property is used instead /// </param> /// <returns>true if rendering succeeds, false on failure - check ErrorMessage</returns> public bool RenderTemplate(string relativePath, object context, string outputFile) { if (outputFile == null) outputFile = RenderingOutputFile; try { using (StreamWriter writer = new StreamWriter(outputFile, false, Engine.Configuration.OutputEncoding, Engine.Configuration.StreamBufferSize)) { return RenderTemplate(relativePath, context, writer); } } catch (Exception ex) { this.SetError(ex.Message); return false; } return true; } /// <summary> /// Renders a template to string. Useful for RenderTemplate /// </summary> /// <param name="relativePath"></param> /// <param name="context"></param> /// <returns></returns> public string RenderTemplateToString(string relativePath, object context) { string result = string.Empty; try { using (StringWriter writer = new StringWriter()) { // String result will be empty as output will be rendered into the // Response object's stream output. However a null result denotes // an error if (!RenderTemplate(relativePath, context, writer)) { this.SetError(Engine.ErrorMessage); return null; } result = writer.ToString(); } } catch (Exception ex) { this.SetError(ex.Message); return null; } return result; } The idea is that you can create custom host container implementations that do exactly what you want fairly easily. Take a look at both the RazorFolderHostContainer and RazorStringHostContainer classes for the basic concepts you can use to create custom implementations. Notice also that you can set the engine’s PerRequestConfigurationData() from the host container: // Set configuration data that is to be passed to the template (any object) Engine.TemplatePerRequestConfigurationData = new RazorFolderHostTemplateConfiguration() { TemplatePath = Path.Combine(this.TemplatePath, relativePath), TemplateRelativePath = relativePath, }; which when set to a non-null value is passed to the Template’s InitializeTemplate() method. This method receives an object parameter which you can cast as needed: public override void InitializeTemplate(object configurationData) { // Pick up configuration data and stuff into Request object RazorFolderHostTemplateConfiguration config = configurationData as RazorFolderHostTemplateConfiguration; this.Request.TemplatePath = config.TemplatePath; this.Request.TemplateRelativePath = config.TemplateRelativePath; } With this data you can then configure any custom properties or objects on your main template class. It’s an easy way to pass data from the HostContainer all the way down into the template. The type you use is of type object so you have to cast it yourself, and it must be serializable since it will likely run in a separate AppDomain. This might seem like an ugly way to pass data around – normally I’d use an event delegate to call back from the engine to the host, but since this is running over AppDomain boundaries events get really tricky and passing a template instance back up into the host over AppDomain boundaries doesn’t work due to serialization issues. So it’s easier to pass the data from the host down into the template using this rather clumsy approach of set and forward. It’s ugly, but it’s something that can be hidden in the host container implementation as I’ve done here. It’s also not something you have to do in every implementation so this is kind of an edge case, but I know I’ll need to pass a bunch of data in some of my applications and this will be the easiest way to do so. Summing Up Hosting the Razor runtime is something I got jazzed up about quite a bit because I have an immediate need for this type of templating/merging/scripting capability in an application I’m working on. I’ve also been using templating in many apps and it’s always been a pain to deal with. The Razor engine makes this whole experience a lot cleaner and more light weight and with these wrappers I can now plug .NET based templating into my code literally with a few lines of code. That’s something to cheer about… I hope some of you will find this useful as well… Resources The examples and code require that you download the Razor runtimes. Projects are for Visual Studio 2010 running on .NET 4.0 Platform Installer 3.0 (install WebMatrix or MVC 3 for Razor Runtimes) Latest Code in Subversion Repository Download Snapshot of the Code Documentation (CHM Help File) © Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  .NET  

    Read the article

  • How to connect to bluetoothbee device using j2me?

    - by user1500412
    I developed a simple bluetooth connection application in j2me. I try it on emulator, both server and client can found each other, but when I deploy the application to blackberry mobile phone and connect to a bluetoothbee device it says service search no records. What could it be possibly wrong? is it j2me can not find a service in bluetoothbee? The j2me itself succeed to found the bluetoothbee device, but why it can not find the service? My code is below. What I don't understand is the UUID? how to set UUID for unknown source? since I didn't know the UUID for the bluetoothbee device. class SearchingDevice extends Canvas implements Runnable,CommandListener,DiscoveryListener{ //...... public SearchingDevice(MenuUtama midlet, Display display){ this.display = display; this.midlet = midlet; t = new Thread(this); t.start(); timer = new Timer(); task = new TestTimerTask(); /*--------------------Device List------------------------------*/ select = new Command("Pilih",Command.OK,0); back = new Command("Kembali",Command.BACK,0); btDevice = new List("Pilih Device",Choice.IMPLICIT); btDevice.addCommand(select); btDevice.addCommand(back); btDevice.setCommandListener(this); /*------------------Input Form---------------------------------*/ formInput = new Form("Form Input"); nama = new TextField("Nama","",50,TextField.ANY); umur = new TextField("Umur","",50,TextField.ANY); measure = new Command("Ukur",Command.SCREEN,0); gender = new ChoiceGroup("Jenis Kelamin",Choice.EXCLUSIVE); formInput.addCommand(back); formInput.addCommand(measure); gender.append("Pria", null); gender.append("Wanita", null); formInput.append(nama); formInput.append(umur); formInput.append(gender); formInput.setCommandListener(this); /*---------------------------------------------------------------*/ findDevice(); } /*----------------Gambar screen searching device---------------------------------*/ protected void paint(Graphics g) { g.setColor(0,0,0); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(255,255,255); g.drawString("Mencari Device", 20, 20, Graphics.TOP|Graphics.LEFT); if(this.counter == 1){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); } if(this.counter == 2){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); } if(this.counter == 3){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); g.setColor(255,115,200); g.fillRect(100, 60, 20, 60); } if(this.counter == 4){ g.setColor(255,115,200); g.fillRect(20, 100, 20, 20); g.setColor(100,255,255); g.fillRect(60, 80, 20, 40); g.setColor(255,115,200); g.fillRect(100, 60, 20, 60); g.setColor(100,255,255); g.fillRect(140, 40, 20, 80); //display.callSerially(this); } } /*--------- Running Searching Screen ----------------------------------------------*/ public void run() { while(run){ this.counter++; if(counter > 4){ this.counter = 1; } try { Thread.sleep(1000); } catch (InterruptedException ex) { System.out.println("interrupt"+ex.getMessage()); } repaint(); } } /*-----------------------------cari device bluetooth yang -------------------*/ public void findDevice(){ try { devices = new java.util.Vector(); local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); local.setDiscoverable(DiscoveryAgent.GIAC); agent.startInquiry(DiscoveryAgent.GIAC, this); } catch (BluetoothStateException ex) { System.out.println("find device"+ex.getMessage()); } } /*-----------------------------jika device ditemukan--------------------------*/ public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) { devices.addElement(rd); } /*--------------Selesai tes koneksi ke bluetooth server--------------------------*/ public void inquiryCompleted(int param) { switch(param){ case DiscoveryListener.INQUIRY_COMPLETED: //inquiry completed normally if(devices.size()>0){ //at least one device has been found services = new java.util.Vector(); this.findServices((RemoteDevice)devices.elementAt(0)); this.run = false; do_alert("Inquiry completed",4000); }else{ do_alert("No device found in range",4000); } break; case DiscoveryListener.INQUIRY_ERROR: do_alert("Inquiry error",4000); break; case DiscoveryListener.INQUIRY_TERMINATED: do_alert("Inquiry canceled",4000); break; } } /*-------------------------------Cari service bluetooth server----------------------------*/ public void findServices(RemoteDevice device){ try { // int[] attributes = {0x100,0x101,0x102}; UUID[] uuids = new UUID[1]; //alamat server uuids[0] = new UUID("F0E0D0C0B0A000908070605040302010",false); //uuids[0] = new UUID("8841",true); //menyiapkan device lokal local = LocalDevice.getLocalDevice(); agent = local.getDiscoveryAgent(); //mencari service dari server agent.searchServices(null, uuids, device, this); //server = (StreamConnectionNotifies)Connector.open(url.toString()); } catch (BluetoothStateException ex) { // ex.printStackTrace(); System.out.println("Errorx"+ex.getMessage()); } } /*---------------------------Pencarian service selesai------------------------*/ public void serviceSearchCompleted(int transID, int respCode) { switch(respCode){ case DiscoveryListener.SERVICE_SEARCH_COMPLETED: if(currentDevice == devices.size() - 1){ if(services.size() > 0){ this.run = false; display.setCurrent(btDevice); do_alert("Service found",4000); }else{ do_alert("The service was not found",4000); } }else{ currentDevice++; this.findServices((RemoteDevice)devices.elementAt(currentDevice)); } break; case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE: do_alert("Device not Reachable",4000); break; case DiscoveryListener.SERVICE_SEARCH_ERROR: do_alert("Service search error",4000); break; case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS: do_alert("No records return",4000); break; case DiscoveryListener.SERVICE_SEARCH_TERMINATED: do_alert("Inquiry canceled",4000); break; } } public void servicesDiscovered(int i, ServiceRecord[] srs) { for(int x=0; x<srs.length;x++) services.addElement(srs[x]); try { btDevice.append(((RemoteDevice)devices.elementAt(currentDevice)).getFriendlyName(false),null); } catch (IOException ex) { System.out.println("service discover"+ex.getMessage()); } } public void do_alert(String msg, int time_out){ if(display.getCurrent() instanceof Alert){ ((Alert)display.getCurrent()).setString(msg); ((Alert)display.getCurrent()).setTimeout(time_out); }else{ Alert alert = new Alert("Bluetooth"); alert.setString(msg); alert.setTimeout(time_out); display.setCurrent(alert); } } private String getData(){ System.out.println("getData"); String cmd=""; try { ServiceRecord service = (ServiceRecord)services.elementAt(btDevice.getSelectedIndex()); String url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); conn = (StreamConnection)Connector.open(url); DataInputStream in = conn.openDataInputStream(); int i=0; timer.schedule(task, 15000); char c1; while(time){ //while(((c1 = in.readChar())>0) && (c1 != '\n')){ //while(((c1 = in.readChar())>0) ){ c1 = in.readChar(); cmd = cmd + c1; //System.out.println(c1); // } } System.out.print("cmd"+cmd); if(time == false){ in.close(); conn.close(); } } catch (IOException ex) { System.err.println("Cant read data"+ex); } return cmd; } //timer task fungsinya ketika telah mencapai waktu yg dijadwalkan putus koneksi private static class TestTimerTask extends TimerTask{ public TestTimerTask() { } public void run() { time = false; } } }

    Read the article

  • It&rsquo;s ok to throw System.Exception&hellip;

    - by Chris Skardon
    No. No it’s not. It’s not just me saying that, it’s the Microsoft guidelines: http://msdn.microsoft.com/en-us/library/ms229007.aspx  Do not throw System.Exception or System.SystemException. Also – as important: Do not catch System.Exception or System.SystemException in framework code, unless you intend to re-throw.. Throwing: Always, always try to pick the most specific exception type you can, if the parameter you have received in your method is null, throw an ArgumentNullException, value received greater than expected? ArgumentOutOfRangeException. For example: public void ArgChecker(int theInt, string theString) { if (theInt < 0) throw new ArgumentOutOfRangeException("theInt", theInt, "theInt needs to be greater than zero."); if (theString == null) throw new ArgumentNullException("theString"); if (theString.Length == 0) throw new ArgumentException("theString needs to have content.", "theString"); } Why do we want to do this? It’s a lot of extra code when compared with a simple: public void ArgChecker(int theInt, string theString) { if (theInt < 0 || string.IsNullOrWhiteSpace(theString)) throw new Exception("The parameters were invalid."); } It all comes down to a couple of things; the catching of the exceptions, and the information you are passing back to the calling code. Catching: Ok, so let’s go with introduction level Exception handling, taught by many-a-university: You do all your work in a try clause, and catch anything wrong in the catch clause. So this tends to give us code like this: try { /* All the shizzle */ } catch { /* Deal with errors */ } But of course, we can improve on that by catching the exception so we can report on it: try { } catch(Exception ex) { /* Log that 'ex' occurred? */ } Now we’re at the point where people tend to go: Brilliant, I’ve got exception handling nailed, what next??? and code gets littered with the catch(Exception ex) nastiness. Why is it nasty? Let’s imagine for a moment our code is throwing an ArgumentNullException which we’re catching in the catch block and logging. Ok, the log entry has been made, so we can debug the code right? We’ve got all the info… What about an OutOfMemoryException – what can we do with that? That’s right, not a lot, chances are you can’t even log it (you are out of memory after all), but you’ve caught it – and as such - have hidden it. So, as part of this, there are two things you can do one, is the rethrow method: try { /* code */ } catch (Exception ex) { //Log throw; } Note, it’s not catch (Exception ex) { throw ex; } as that will wipe all your important stack trace information. This does get your exception to continue, and is the only reason you would catch Exception (anywhere other than a global catch-all) in your code. The other preferred method is to catch the exceptions you can deal with. It may not matter that the string I’m passing in is null, and I can cope with it like this: try{ DoSomething(myString); } catch(ArgumentNullException){} And that’s fine, it means that any exceptions I can’t deal with (OutOfMemory for example) will be propagated out to other code that can deal with it. Of course, this is horribly messy, no one wants try / catch blocks everywhere and that’s why Microsoft added the ‘Try’ methods to the framework, and it’s a strategy we should continue. If I try: int i = (int) "one"; I will get an InvalidCastException which means I need the try / catch block, but I could mitigate this using the ‘TryParse’ method: int i; if(!Int32.TryParse("one", out i)) return; Similarly, in the ‘DoSomething’ example, it might be beneficial to have a ‘TryDoSomething’ that returns a boolean value indicating the success of continuing. Obviously this isn’t practical in every case, so use the ol’ common sense approach. Onwards Yer thanks Chris, I’m looking forward to writing tonnes of new code. Fear not, that is where helpers come into it… (but that’s the next post)

    Read the article

  • Logging errors caused by exceptions deep in the application

    - by Kaleb Pederson
    What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error? For example, let's say that I have an ETL system whose transform step involves: a transformer, pipeline, processing algorithm, and processing engine. In brief, the transformer takes in an input file, parses out records, and sends the records through the pipeline. The pipeline aggregates the results of the processing algorithm (which could do serial or parallel processing). The processing algorithm sends each record through one or more processing engines. So, I have at least four levels: Transformer - Pipeline - Algorithm - Engine. My code might then look something like the following: class Transformer { void Process(InputSource input) { try { var inRecords = _parser.Parse(input.Stream); var outRecords = _pipeline.Transform(inRecords); } catch (Exception ex) { var inner = new ProcessException(input, ex); _logger.Error("Unable to parse source " + input.Name, inner); throw inner; } } } class Pipeline { IEnumerable<Result> Transform(IEnumerable<Record> records) { // NOTE: no try/catch as I have no useful information to provide // at this point in the process var results = _algorithm.Process(records); // examine and do useful things with results return results; } } class Algorithm { IEnumerable<Result> Process(IEnumerable<Record> records) { var results = new List<Result>(); foreach (var engine in Engines) { foreach (var record in records) { try { engine.Process(record); } catch (Exception ex) { var inner = new EngineProcessingException(engine, record, ex); _logger.Error("Engine {0} unable to parse record {1}", engine, record); throw inner; } } } } } class Engine { Result Process(Record record) { for (int i=0; i<record.SubRecords.Count; ++i) { try { Validate(record.subRecords[i]); } catch (Exception ex) { var inner = new RecordValidationException(record, i, ex); _logger.Error( "Validation of subrecord {0} failed for record {1}", i, record ); } } } } There's a few important things to notice: A single error at the deepest level causes three log entries (ugly? DOS?) Thrown exceptions contain all important and useful information Logging only happens when failure to do so would cause loss of useful information at a lower level. Thoughts and concerns: I don't like having so many log entries for each error I don't want to lose important, useful data; the exceptions contain all the important but the stacktrace is typically the only thing displayed besides the message. I can log at different levels (e.g., warning, informational) The higher level classes should be completely unaware of the structure of the lower-level exceptions (which may change as the different implementations are replaced). The information available at higher levels should not be passed to the lower levels. So, to restate the main questions: What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error?

    Read the article

  • chkdsk "An unspecified error occurred (696e647863686b2e e19)"

    - by Ex Umbris
    System is Win7x64 Pro on Core i7-920, 12GB I'm experiencing some system flakiness and am trying to pin down the cause. SMART shows zero bad sectors, zero pending reallocations on all drives Memory tests show no problems. Chkdsk fails in various different ways: When run from a normal command line (no /f option) it gets to 63% and then hangs When run on boot (autocheck) it hangs immediately on starting. Actually, the countdown timer (Press any key to skip chkdsk) gets to 1 second and the system hangs. When run from the F8 "Repair System" option (the Win7 "recovery console"), with /f, it runs to about 63% (end of stage 2) and then fails as follows:   Volume label is OS. CHKDSK is verifying files (stage 1 of 3)... 5068288 file records processed. File verification completed. 308 large file records processed. 0 bad file records processed. 2 EA records processed. 77 reparse records processed. CHKDSK is verifying indexes (stage 2 of 3)... 63 percent complete. (6078872 of 7562028 index entries processed) An unspecified error occurred (696e647863686b2e e19). Unable to obtain a handle to the event log. Googling and searching on Technet for the error code and "Unable to obtain a handle to the event log" both turn up nothing useful. Anybody have any info on what the problem is?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >