Daily Archives

Articles indexed Saturday June 9 2012

Page 7/15 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Downloading a file in ASP.NET (through the server) while streaming it to the user

    - by James Teare
    My ASP.NET website currently downloads a file from a remote server to a local drive, although when users access the site they have to wait for the server to finish downloading the file until they can then download the file from my ASP.NET website. Is it possible to almost stream the download from the remote website - through my ASP.NET website directly to the user (a bit like a proxy) ? My current code is as follows: using (var client = new WebClientEx()) { client.DownloadFile(downloadURL, "outputfile.zip"); } WebClient class: public class WebClientEx : WebClient { public CookieContainer CookieContainer { get; private set; } public WebClientEx() { CookieContainer = new CookieContainer(); } protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = CookieContainer; } return request; } }

    Read the article

  • Rails: Different prices for different branches, association depending on two other models combined

    - by Greg Lemond
    I have three models: Service has_many :prices has_many :groups, through: prices Price belongs_to :service belongs_to :group Group has_many :prices I want to have an input field (Simple_Form) for every price. In views/services/_form.html.haml I do: simple_form_for @service do |f| simple_fields_for :groups do |g| simple_fields_for :prices do |p| p.input :price With this setup I only get input fields for already saved prices. How I can get a price field for every group? I tried to do it manually, but it got really nasty and didn't work either. Thanks for any ideas!

    Read the article

  • Drag a UIView from one UIScrollView to another

    - by theDuncs
    I have two UIScrollViews on my screen and I need to be able to drag a UIView from one scrollview to the other. At the moment, I have a UILongGestureRecognizer on the UIView that I want to move, such that when the user starts dragging it, I make the view follow the touch: - (void)dragChild:(UILongPressGestureRecognizer *)longPress { [[longPress view] setCenter:[longPress locationInView:[[longPress view] superview]]]; } But when I get the boundary of the starting UIScrollView, the view disappears because it's locked into that scrollview's bounds. Is there a way to "pop" it out of the scrollview when I start dragging such that I can carry it over to the other scrollview? Also, how do I test for the "drop" location? I want to know if it's been dropped over a certain other view. Or am I going about this all the wrong way? Thanks guys

    Read the article

  • Android: How to close a cursor that returns from Class to Activity

    - by Daniel
    I have: Accounts.java public class Accounts{ private SQLiteDatabase dbConfig; public Cursor list(Context context, String db, String where, String order) { DBHelper dbHelper = new DBHelper(context, db); dbConfig = dbHelper.getReadableDatabase(); Cursor c = dbConfig.query("accounts", new String[]{ "iId","sName"}, where, null, null, null, order); return c; } } and: MainActivity.java Accounts account = new Accounts(); Cursor cursor = account.list(getApplicationContext(), globalDB, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(0); String name = cursor.getString(1); } cursor.close(); Running my application I get some logcat messages like: close() was never explicitly called on database... What is the best way to prevent it? How can I close a Cursor that returns from other class? Thanks

    Read the article

  • Embedding generic sql queries into c# program

    - by Pooja Balkundi
    Okay referring to my first question code in the main, I want the user to enter employee name at runtime and then i take this name which user has entered and compare it with the e_name of my emp table , if it exists i want to display all information of that employee , how can I achieve this ? using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace ConnectCsharppToMySQL { public class DBConnect { private MySqlConnection connection; private string server; private string database; private string uid; private string password; string name; //Constructor public DBConnect() { Initialize(); } //Initialize values private void Initialize() { server = "localhost"; database = "test"; uid = "root"; password = ""; string connectionString; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; connection = new MySqlConnection(connectionString); } //open connection to database private bool OpenConnection() { try { connection.Open(); return true; } catch (MySqlException ex) { //When handling errors, you can your application's response based //on the error number. //The two most common error numbers when connecting are as follows: //0: Cannot connect to server. //1045: Invalid user name and/or password. switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server. Contact administrator"); break; case 1045: MessageBox.Show("Invalid username/password, please try again"); break; } return false; } } //Close connection private bool CloseConnection() { try { connection.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return false; } } //Insert statement public void Insert() { string query = "INSERT INTO emp (e_name, age) VALUES('Pooja R', '21')"; //open connection if (this.OpenConnection() == true) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command cmd.ExecuteNonQuery(); //close connection this.CloseConnection(); } } //Update statement public void Update() { string query = "UPDATE emp SET e_name='Peachy', age='22' WHERE e_name='Pooja R'"; //Open connection if (this.OpenConnection() == true) { //create mysql command MySqlCommand cmd = new MySqlCommand(); //Assign the query using CommandText cmd.CommandText = query; //Assign the connection using Connection cmd.Connection = connection; //Execute query cmd.ExecuteNonQuery(); //close connection this.CloseConnection(); } } //Select statement public List<string>[] Select() { string query = "SELECT * FROM emp where e_name=(/*I WANT USER ENTERED NAME TO GET INSERTED HERE*/)"; //Create a list to store the result List<string>[] list = new List<string>[3]; list[0] = new List<string>(); list[1] = new List<string>(); list[2] = new List<string>(); //Open connection if (this.OpenConnection() == true) { //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list while (dataReader.Read()) { list[0].Add(dataReader["e_id"] + ""); list[1].Add(dataReader["e_name"] + ""); list[2].Add(dataReader["age"] + ""); } //close Data Reader dataReader.Close(); //close Connection this.CloseConnection(); //return list to be displayed return list; } else { return list; } } public static void Main(String[] args) { DBConnect db1 = new DBConnect(); Console.WriteLine("Initializing"); db1.Initialize(); Console.WriteLine("Search :"); Console.WriteLine("Enter the employee name"); db1.name = Console.ReadLine(); db1.Select(); Console.ReadLine(); } } }

    Read the article

  • FFT and IFFT on 3D matrix (Matlab)

    - by SteffenDM
    I have a movie with 70 grayscale frames in MATLAB. I have put them in a 3-D matrix, so the dimensions are X, Y and time. I want to determine the frequencies in the time dimension, so I have to calculate the FFT for every point in the 3rd dimension. This is not a problem but I have to return the images to the original form with ifft. In a normal situation this would be true: X = ifft(fft(X)), but this is not the case it seems in MATLAB when you work with multidimensional data. This is the code I use: for i = 1:length y(:, :, i) = [img1{i, level}]; %# take each picture from an cell array and put it end %# and put it in 3D array y2 = ifft(fft(y, NFFT,3), NFFT, 3); %# NFFT = 128, the 3 is the dimension in which i want %# to calculate the FFT and IFFT y is 480x640x70, so there are 70 images of 640x480 pixels. If I use only fft, y2 is 480x640x128 (this is normal because we want 128 points with NFFT). If I use fft and ifft, y2 is 480x640x128 pixels. This is not normal, the 128 should be 70 again. I tried to do it in just one dimension by using 2 for loops and this works fine. The for loops take to much time, though.

    Read the article

  • How to use sessions in PDO?

    - by Byakugan
    I am still redoing and getting rid of old mysql_* commands in my code. I tried to transfer my session login form old code and this is what I got so far: public function login($user, $password) { if (!empty($user) && !empty($password)) { $password = $web->doHash($user, $password); // in this function is (return sha1(strtoupper($user).':'.strtoupper($password)) $stmt = $db_login->prepare("SELECT * FROM account WHERE username=:user AND pass_hash=:password"); $stmt->bindValue(':user', $user, PDO::PARAM_STR); $stmt->bindValue(':password', $password, PDO::PARAM_STR); $stmt->execute(); $rows = $stmt->rowCount(); if ($rows > 0) { $results_login = $stmt->fetch(PDO::FETCH_ASSOC); $_SESSION['user_name'] = $results_login['username']; $_SESSION['user_id'] = $results_login['id']; return true; } else { return false; } } else { return false; } } After that I am using checks if user logged on site: public function isLogged() { return (!empty($_SESSION['user_id']) && !empty($_SESSION['user_name'])); } But it seems - this function returns always empty because $_SESSION does not exists in PDO? And of course logout is used in this form on my sites: public function logout() { unset($_SESSION['user_id']); unset($_SESSION['user_name']); } But I think PDO has different way of handling session? I did not find any so what is it can i somehow add $_SESSION in PDO withou changing code much? I am using variables $_SESSION['user_name'] and $_SESSION['user_id'] in all over my web project. Summary: 1) How to use sessions in PDO correctly? 2) What is difference between using $stmt->fetch(PDO::FETCH_ASSOC); and $stmt->fetchAll(); Thank you.

    Read the article

  • Git 1.7.10 asks me for github username and password

    - by Daniel Ruf
    Since I have the new version it doesnt ask me anymore for the password I set in my ssh key file. It asks now directly for a github username and password when I push every time. Is this a new feature of git or changed it in the past or is there something what changed on github? I tried to authenticate using ssh and the email and password from my ssh ke file and it worked. Github changed to smartftp and also changed the instructions for setting up repos https://github.com/blog/1104-credential-caching-for-wrist-friendly-git-usage https://help.github.com/articles/create-a-repo Saw it later, they use now https instead of the git protocol

    Read the article

  • How to interrupt a thread performing a blocking socket connect?

    - by Jason R
    I have some code that spawns a pthread that attempts to maintain a socket connection to a remote host. If the connection is ever lost, it attempts to reconnect using a blocking connect() call on its socket. Since the code runs in a separate thread, I don't really care about the fact that it uses the synchronous socket API. That is, until it comes time for my application to exit. I would like to perform some semblance of an orderly shutdown, so I use thread synchronization primitives to wake up the thread and signal for it to exit, then perform a pthread_join() on the thread to wait for it to complete. This works great, unless the thread is in the middle of a connect() call when I command the shutdown. In that case, I have to wait for the connect to time out, which could be a long time. This makes the application appear to take a long time to shut down. What I would like to do is to interrupt the call to connect() in some way. After the call returns, the thread will notice my exit signal and shut down cleanly. Since connect() is a system call, I thought that I might be able to intentionally interrupt it using a signal (thus making the call return EINTR), but I'm not sure if this is a robust method in a POSIX threads environment. Does anyone have any recommendations on how to do this, either using signals or via some other method? As a note, the connect() call is down in some library code that I cannot modify, so changing to a non-blocking socket is not an option.

    Read the article

  • HTML5 Canvas and Game Programming

    - by LemonBeagle
    I hope this isn't too open ended. I'm wondering if there is a better (more battery-friendly) way of doing this -- I have a small HTML 5 game, drawn in a canvas (let's say 500x500). I have some objects whose positions I update every 50ms or so. My current implementation re-draws the entire canvas every 50ms. I can't imagine that being very good for battery life on mobile platforms. Is there a better way to do this? This must be a common pattern with games. EDIT: as requested, here are some more updates: Right now, the objects are geometric primitives drawn via arcs and lines. I'm not opposed to making these small png/jpg/gif files instead of that'd help out. These are small graphics -- just 15x15 or so. As the game progresses, more and more of the screen changes at a time. However, at the start, the screen changes relatively slowly (the objects randomly moved a few pixels every 50ms).

    Read the article

  • Struts2 Tiles in Google app engine

    - by user365941
    I am trying to build an java web application using struts2 and tiles in Google App Engine. Below is my tiles.xml file <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" "http://tiles.apache.org/dtds/tiles-config_2_0.dtd"> <tiles-definitions> <definition name="baseLayout" template="BaseLayout.jsp"> <put-attribute name="title" value="" /> <put-attribute name="header" value="Header.jsp" /> <put-attribute name="body" value="" /> <put-attribute name="footer" value="Footer.jsp" /> </definition> <definition name="/welcome.tiles" extends="baseLayout"> <put-attribute name="title" value="Welcome" /> <put-attribute name="body" value="Welcome.jsp" /> </definition> </tiles-definitions> But when I run the app,I am not getting any error. it just prints "Header.jsp Welcome.jsp Footer.jsp". It does not show the actual jsp pages. Please advise on what needs to be done. Thanks in advance Regards

    Read the article

  • Spring MVC with a rich client framework

    - by ziggy
    I have several applications that are structured as follows DataComponent WebComponent ThickClientComponent WebServices The DataComponent has all the functionality required to access the application's data so it contains the DAOs and the JPA entities. The other three modules are: WebComponent - A spring MVC application that uses the DataComponent for data acccess ThickClientComponent- A Swing application that uses the DataComponent for data access WebServices - A SOAP based services that also uses the DataComponent. All three projets have the DataComponent as a dependeny in their Maven POM file. I would like to use a rich client framework like RichFaces, icefaces or primefaces as i need to be able to use the rich components are available in rich client frameworks (i.e. trees, panel, drag and drop etc). I have looked around and i cant seem to find an example where a Spring MVC application uses a rich client platform. Is it possible? Are the rich client platforms a framework meaning that i have to use either Spring MVC or the rich client platform but not both? The DataComponent module is spring based.

    Read the article

  • Restarting explorer from a batch file only opens an explorer window

    - by Ben Hooper
    In one part of a batch file (kind of), I need to restart Explorer. I use the following method to accomplish this: taskkill /f /im explorer.exe >nul explorer.exe :: I have also tried: %winDir%\explorer.exe :: start %winDir%\explorer.exe :: start /b %winDir%\explorer.exe :: start /d %winDir%\explorer.exe (as suggested by panda-34) :: :: I've even tried delaying the above commands with: ping localhost -n 11 >nul Then this happens: explorer.exe is successfully terminated (denoted by the lack of taskbar and desktop) An explorer window opens, which I am left with indefinitely (see Image 1) I can only then restart explorer by manually starting a new process from Task Manager (Win + R doesn't respond), even though explorer.exe is actually already in the process list, strangely enough.. (see Image 2)   Now, I say "kind of" as I'm running the batch file from a self-executing SFX archive, created with WinRAR. When executed, the contents of the archive are extracted to %temp% and a user-defined bootstrapper (in this case, my batch file) is run upon successful extraction. The strangest thing about it, though, is that if you manually extract the contents of the archive and run the batch file then explorer restarts correctly. It only ever glitches when called from an SFX. I'm experiencing this glitch on Windows 7 x64.   Link to an SFX archive demonstrating this, if anyone wants it: https://dl.dropbox.com/u/27573003/Social%20Distribution/restart-explorer.exe Image 1: Image 2:

    Read the article

  • python Socket.IO client for sending broadcast messages to TornadIO2 server

    - by Alp
    I am building a realtime web application. I want to be able to send broadcast messages from the server-side implementation of my python application. Here is the setup: socketio.js on the client-side TornadIO2 server as Socket.IO server python on the server-side (Django framework) I can succesfully send socket.io messages from the client to the server. The server handles these and can send a response. In the following i will describe how i did that. Current Setup and Code First, we need to define a Connection which handles socket.io events: class BaseConnection(tornadio2.SocketConnection): def on_message(self, message): pass # will be run if client uses socket.emit('connect', username) @event def connect(self, username): # send answer to client which will be handled by socket.on('log', function) self.emit('log', 'hello ' + username) Starting the server is done by a Django management custom method: class Command(BaseCommand): args = '' help = 'Starts the TornadIO2 server for handling socket.io connections' def handle(self, *args, **kwargs): autoreload.main(self.run, args, kwargs) def run(self, *args, **kwargs): port = settings.SOCKETIO_PORT router = tornadio2.TornadioRouter(BaseConnection) application = tornado.web.Application( router.urls, socket_io_port = port ) print 'Starting socket.io server on port %s' % port server = SocketServer(application) Very well, the server runs now. Let's add the client code: <script type="text/javascript"> var sio = io.connect('localhost:9000'); sio.on('connect', function(data) { console.log('connected'); sio.emit('connect', '{{ user.username }}'); }); sio.on('log', function(data) { console.log("log: " + data); }); </script> Obviously, {{ user.username }} will be replaced by the username of the currently logged in user, in this example the username is "alp". Now, every time the page gets refreshed, the console output is: connected log: hello alp Therefore, invoking messages and sending responses works. But now comes the tricky part. Problems The response "hello alp" is sent only to the invoker of the socket.io message. I want to broadcast a message to all connected clients, so that they can be informed in realtime if a new user joins the party (for example in a chat application). So, here are my questions: How can i send a broadcast message to all connected clients? How can i send a broadcast message to multiple connected clients that are subscribed on a specific channel? How can i send a broadcast message anywhere in my python code (outside of the BaseConnection class)? Would this require some sort of Socket.IO client for python or is this builtin with TornadIO2? All these broadcasts should be done in a reliable way, so i guess websockets are the best choice. But i am open to all good solutions.

    Read the article

  • Why are changes to coffeescript files not being compiled when my Rails 3.2.0 app is in development mode?

    - by ben
    Normally, any changes I make to .js.coffee files in my Rails 3.2.0 app in development mode take effect when I refresh the page. All of a sudden, this is not happening. If I do rake assets:precompile, then the changes are shown, but then if I do rake assets:clean they go back to not being shown. What is causing this? Edit: Restarting the server makes the changes show. Why isn't this happening automatically as before? Edit: Here is my development.rb Myapp::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true config.action_mailer.default_url_options = { :host => 'localhost:3000' } config.log_level = :warn end

    Read the article

  • Getting snapshot from webcam in Matlab

    - by Harsh
    I have created a simple GUI to preview webcam stream and to get snapshot from it. For this I have created on axes to show video, one push button(pushbutton1) to start preview, one push button(pushbutton2) to get snapshot. Following is the code for these two push buttons. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) axes(handles.axes1); vidObj = videoinput('winvideo',1); videoRes = get(vidObj, 'VideoResolution'); numberOfBands = get(vidObj, 'NumberOfBands'); handleToImage = image( zeros([videoRes(2), videoRes(1), numberOfBands], 'uint8') ); preview(vidObj, handleToImage); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) a=getsnapshot(get(axes,'Children')); imshow(a); In pushbutton2_Callback I am trying to get child of axes ie. vidObj. But this gives me error ??? Undefined function or method 'getsnapshot' for input arguments of type 'double'.. Why is it returing double type instead of child object vidObj? How can I fix it and get snapshot? Is there any other better way? (I just started learning GUI.) Thanks.

    Read the article

  • Eclipse 3.7 Classic Nightmare - ADT Installation

    - by Cal
    I've been trying to install the ADT for Eclipse Classic 3.7 to no avail. From what I've seen on searches, the general consensus seems to be to update the software, but alas I cannot do that, either. BELOW: An example of the error message received when trying to update Eclipse, or when attempting to install from a web location. Some sites could not be found. See the error log for more detail. Unable to read repository at http://download.eclipse.org/eclipse/updates/3.7/content.xml. Cannot assign requested address: JVM_Bind I followed the troubleshooting recommendations of Google/Android's developer section, and attempted to install ADT via archive. BELOW: The resulting error from attempting to install via archive. Cannot complete the install because one or more required items could not be found. Software being installed: Android Development Tools 11.0.0.v201105251008-128486 (com.android.ide.eclipse.adt.feature.group 11.0.0.v201105251008-128486) Missing requirement: Android Development Tools 11.0.0.v201105251008-128486 (com.android.ide.eclipse.adt.feature.group 11.0.0.v201105251008-128486) requires 'org.eclipse.gef 0.0.0' but it could not be found Now, from what I hear, the inability to update/install via Internet seems to be a proxy-related issue, however I don't believe that I'm under any such thing (I'm just using my computer connected to my home network for this). I'm using the most up-to-date versions of anything I can think of (ADT, Eclipse, SDK Tools etc). I'm using Windows 7 Ultimate 64bit, and am using the 64bit version of Eclipse Classic.

    Read the article

  • How to call stored procedure by hibernate?

    - by user367097
    Hi I have an oracle stored procedure GET_VENDOR_STATUS_COUNT(DOCUMENT_ID IN NUMBER , NOT_INVITED OUT NUMBER,INVITE_WITHDRAWN OUT NUMBER,... rest all parameters are OUT parameters. In hbm file I have written - <sql-query name="getVendorStatus" callable="true"> <return-scalar column="NOT_INVITED" type="string"/> <return-scalar column="INVITE_WITHDRAWN" type="string"/> <return-scalar column="INVITED" type="string"/> <return-scalar column="DISQUALIFIED" type="string"/> <return-scalar column="RESPONSE_AWAITED" type="string"/> <return-scalar column="RESPONSE_IN_PROGRESS" type="string"/> <return-scalar column="RESPONSE_RECEIVED" type="string"/> { call GET_VENDOR_STATUS_COUNT(:DOCUMENT_ID , :NOT_INVITED ,:INVITE_WITHDRAWN ,:INVITED ,:DISQUALIFIED ,:RESPONSE_AWAITED ,:RESPONSE_IN_PROGRESS ,:RESPONSE_RECEIVED ) } </sql-query> In java I have written - session.getNamedQuery("getVendorStatus").setParameter("DOCUMENT_ID", "DOCUMENT_ID").setParameter("NOT_INVITED", "NOT_INVITED") ... continue till all the parametes . I am getting the sql exception 18:29:33,056 WARN [JDBCExceptionReporter] SQL Error: 1006, SQLState: 72000 18:29:33,056 ERROR [JDBCExceptionReporter] ORA-01006: bind variable does not exist Please let me know what is the exact process of calling a stored procedure from hibernate. I do not want to use JDBC callable statement.

    Read the article

  • simple fbml fb:login-button is not rendering in ie6

    - by Mark
    The following codes works in FF and Chrome, but IE6 does not render the connect button. What am I missing here? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title></title> </head> <body> <fb:login-button>Login button</fb:login-button> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script> <script type="text/javascript"> FB_RequireFeatures(["XFBML"], function(){ FB.Facebook.init("API_KEY", "/xd_receiver.htm"); }); </script> </body> </html>

    Read the article

  • How to get Augmented Reality: A Practical Guide examples working?

    - by Glen
    I recently bought the book: Augmented Reality: A Practical Guide (http://pragprog.com/titles/cfar/augmented-reality). It has example code that it says runs on Windows, MacOS and Linux. But I can't get the binaries to run. Has anyone got this book and got the binaries to run on ubuntu? I also can't figure out how to compile the examples in Ubuntu. How would I do this? Here is what it says to do: Compiling for Linux Refreshingly, there are no changes required to get the programs in this chapter to compile for Linux, but as with Windows, you’ll first have to find your GL and GLUT files. This may mean you’ll have to download the correct version of GLUT for your machine. You need to link in the GL, GLU, and GLUT libraries and provide a path to the GLUT header file and the files it includes. See whether there is a glut.h file in the /usr/include/GL directory; otherwise, look elsewhere for it—you could use the command find / -name "glut.h" to search your entire machine, or you could use the locate command (locate glut.h). You may need to customize the paths, but here is an example of the compile command: gcc -o opengl_template opengl_template.cpp -I /usr/include/GL -I /usr/include -lGL -lGLU -lglut gcc is a C/C++ compiler that should be present on your Linux or Unix machine. The -I /usr/include/GL command-line argument tells gcc to look in /usr/include/GL for the include files. In this case, you’ll find glut.h and what it includes. When linking in libraries with gcc, you use the -lX switch—where X is the name of your library and there is a correspond- ing libX.a file somewhere in your path. For this example, you want to link in the library files libGL.a, libGLU.a, and libglut.a, so you will use the gcc arguments -lGL -lGLU -lglut. These three files are found in the default directory /usr/lib/, so you don’t need to specify their location as you did with glut.h. If you did need to specify the library path, you would add -L to the path. To run your compiled program, type ./opengl_template or, if the current directory is in your shell’s paths, just opengl_template. When working in Linux, it’s important to know that you may need to keep your texture files to a maximum of 256 by 256 pixels or find the settings in your system to raise this limit. Often an OpenGL program will work in Windows but produce a blank white texture in Linux until the texture size is reduced. The above instructions make no sense to me. Do I have to use gcc to compile or can I use eclipse? If I use either eclipse or gcc what do I need to do to compile and run the program?

    Read the article

  • Log message Request and Response in ASP.NET WebAPI

    - by Fredrik N
    By logging both incoming and outgoing messages for services can be useful in many scenarios, such as debugging, tracing, inspection and helping customers with request problems etc.  I have a customer that need to have both incoming and outgoing messages to be logged. They use the information to see strange behaviors and also to help customers when they call in  for help (They can by looking in the log see if the customers sends in data in a wrong or strange way).   Concerns Most loggings in applications are cross-cutting concerns and should not be  a core concern for developers. Logging messages like this:   // GET api/values/5 public string Get(int id) { //Cross-cutting concerns Log(string.Format("Request: GET api/values/{0}", id)); //Core-concern var response = DoSomething(); //Cross-cutting concerns Log(string.Format("Reponse: GET api/values/{0}\r\n{1}", id, response)); return response; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } will only result in duplication of code, and unnecessarily concerns for the developers to be aware of, if they miss adding the logging code, no logging will take place. Developers should focus on the core-concern, not the cross-cutting concerns. By just focus on the core-concern the above code will look like this: // GET api/values/5 public string Get(int id) { return DoSomething(); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The logging should then be placed somewhere else so the developers doesn’t need to focus care about the cross-concern. Using Message Handler for logging There are different ways we could place the cross-cutting concern of logging message when using WebAPI. We can for example create a custom ApiController and override the ApiController’s ExecutingAsync method, or add a ActionFilter, or use a Message Handler. The disadvantage with custom ApiController is that we need to make sure we inherit from it, the disadvantage of ActionFilter, is that we need to add the filter to the controllers, both will modify our ApiControllers. By using a Message Handler we don’t need to do any changes to our ApiControllers. So the best suitable place to add our logging would be in a custom Message Handler. A Message Handler will be used before the HttpControllerDispatcher (The part in the WepAPI pipe-line that make sure the right controller is used and called etc). Note: You can read more about message handlers here, it will give you a good understanding of the WebApi pipe-line. To create a Message Handle we can inherit from the DelegatingHandler class and override the SendAsync method: public class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   If we skip the call to the base.SendAsync our ApiController’s methods will never be invoked, nor other Message Handlers. Everything placed before base.SendAsync will be called before the HttpControllerDispatcher (before WebAPI will take a look at the request which controller and method it should be invoke), everything after the base.SendAsync, will be executed after our ApiController method has returned a response. So a message handle will be a perfect place to add cross-cutting concerns such as logging. To get the content of our response within a Message Handler we can use the request argument of the SendAsync method. The request argument is of type HttpRequestMessage and has a Content property (Content is of type HttpContent. The HttpContent has several method that can be used to read the incoming message, such as ReadAsStreamAsync, ReadAsByteArrayAsync and ReadAsStringAsync etc. Something to be aware of is what will happen when we read from the HttpContent. When we read from the HttpContent, we read from a stream, once we read from it, we can’t be read from it again. So if we read from the Stream before the base.SendAsync, the next coming Message Handlers and the HttpControllerDispatcher can’t read from the Stream because it’s already read, so our ApiControllers methods will never be invoked etc. The only way to make sure we can do repeatable reads from the HttpContent is to copy the content into a buffer, and then read from that buffer. This can be done by using the HttpContent’s LoadIntoBufferAsync method. If we make a call to the LoadIntoBufferAsync method before the base.SendAsync, the incoming stream will be read in to a byte array, and then other HttpContent read operations will read from that buffer if it’s exists instead directly form the stream. There is one method on the HttpContent that will internally make a call to the  LoadIntoBufferAsync for us, and that is the ReadAsByteArrayAsync. This is the method we will use to read from the incoming and outgoing message. public abstract class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var requestMessage = await request.Content.ReadAsByteArrayAsync(); var response = await base.SendAsync(request, cancellationToken); var responseMessage = await response.Content.ReadAsByteArrayAsync(); return response; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The above code will read the content of the incoming message and then call the SendAsync and after that read from the content of the response message. The following code will add more logic such as creating a correlation id to combine the request with the response, and create a log entry etc: public abstract class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId); var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri); var requestMessage = await request.Content.ReadAsByteArrayAsync(); await IncommingMessageAsync(corrId, requestInfo, requestMessage); var response = await base.SendAsync(request, cancellationToken); var responseMessage = await response.Content.ReadAsByteArrayAsync(); await OutgoingMessageAsync(corrId, requestInfo, responseMessage); return response; } protected abstract Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message); protected abstract Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message); } public class MessageLoggingHandler : MessageHandler { protected override async Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message) { await Task.Run(() => Debug.WriteLine(string.Format("{0} - Request: {1}\r\n{2}", correlationId, requestInfo, Encoding.UTF8.GetString(message)))); } protected override async Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message) { await Task.Run(() => Debug.WriteLine(string.Format("{0} - Response: {1}\r\n{2}", correlationId, requestInfo, Encoding.UTF8.GetString(message)))); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   The code above will show the following in the Visual Studio output window when the “api/values” service (One standard controller added by the default WepAPI template) is requested with a Get http method : 6347483479959544375 - Request: GET http://localhost:3208/api/values 6347483479959544375 - Response: GET http://localhost:3208/api/values ["value1","value2"] .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Register a Message Handler To register a Message handler we can use the Add method of the GlobalConfiguration.Configration.MessageHandlers in for example Global.asax: public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler()); ... } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Summary By using a Message Handler we can easily remove cross-cutting concerns like logging from our controllers. You can also find the source code used in this blog post on ForkCan.com, feel free to make a fork or add comments, such as making the code better etc. Feel free to follow me on twitter @fredrikn if you want to know when I will write other blog posts etc.

    Read the article

  • Tales from the Coal Face - Speeding up a C# compilation

    - by TATWORTH
    At one place, I was faced with a C# solution which when XML documentation was turned on, the compilation time increased from 45 seconds to over 8 minutes. This slowdown was unacceptable, however some digging revealed an excellent suggestion by Eric Woodruff at http://social.msdn.microsoft.com/Forums/en-US/devdocs/thread/9bbad4cc-e229-49da-a6f7-3cdf470ac53a/ where he suggested "just suppress the warning by entering it's number (1591 for C#) in the Suppress Warnings field on the Build tab of the project properties". I followed Eric's suggestion and the compilation time went back down to 45 seconds. Now that CS1591 is suppressed how was missing documentation to be found? All that was necessary was to run StyleCop!

    Read the article

  • 7-Zip - A Free alternative to other compression utilities

    - by TATWORTH
    At http://www.7-zip.org/download.html, there is a free alternative other compression utilities. It handles a wide variety of formats including RAR!Here is the description from its home page:License 7-Zip is open source software. Most of the source code is under the GNU LGPL license. The unRAR code is under a mixed license: GNU LGPL + unRAR restrictions. Check license information here: 7-Zip license. You can use 7-Zip on any computer, including a computer in a commercial organization. You don't need to register or pay for 7-Zip. The main features of 7-Zip High compression ratio in 7z format with LZMA and LZMA2 compressionSupported formats: Packing / unpacking: 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIMUnpacking only: ARJ, CAB, CHM, CPIO, CramFS, DEB, DMG, FAT, HFS, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, RAR, RPM, SquashFS, UDF, VHD, WIM, XAR and Z. For ZIP and GZIP formats, 7-Zip provides a compression ratio that is 2-10 % better than the ratio provided by PKZip and WinZipStrong AES-256 encryption in 7z and ZIP formatsSelf-extracting capability for 7z formatIntegration with Windows ShellPowerful File ManagerPowerful command line versionPlugin for FAR ManagerLocalizations for 79 languages

    Read the article

  • New Version of Sandcastle - 2.7.0.0

    - by TATWORTH
    There is a new version of Sandcastle at http://sandcastlestyles.codeplex.com/This is a free tool for producing help files from the XML documentation within C# or VB.NET code.This is a guided installer that prompts you to install the correct components in the correct order.The reason why the download is at http://sandcastlestyles.codeplex.com/ instead of http://sandcastle.codeplex.com/releases/view/47665 is discussed at http://sandcastle.codeplex.com/discussions/288079

    Read the article

  • Microsoft is Top Pick for ALM

    - by Arkham
    Investigating the market for a new software product can be a daunting task. Sometimes it’s difficult to even uncover all of the players. There’s no shortage of rhetoric on each vendor’s web site, but how can today’s CTO get objective information about how a software package ranks against it’s peers in a given space? Every year, Gartner releases what they call a Magic Quadrant report evaluating various products in a given space. This past week, Gartner released their analysis of products in the Application Lifecycle Management (ALM) arena. It is very exciting to see us in the top spot as a thought leader and for our ability to execute. If you are interested in ALM, you can read through an entire reprint of the report here. There’s plenty of new competitors listed and some of the existing competitors have shifted quite a bit. And this comes prior to the release of Team Foundation Server 2012! I suppose with all of the new features in 2012, they could just add another square to the upper-right. It’s beyond awesome! It’s be-awesome!

    Read the article

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