Search Results

Search found 451 results on 19 pages for 'filestream'.

Page 18/19 | < Previous Page | 14 15 16 17 18 19  | Next Page >

  • Recommendations for a C++ polymorphic, seekable, binary I/O interface

    - by Trevor Robinson
    I've been using std::istream and ostream as a polymorphic interface for random-access binary I/O in C++, but it seems suboptimal in numerous ways: 64-bit seeks are non-portable and error-prone due to streampos/streamoff limitations; currently using boost/iostreams/positioning.hpp as a workaround, but it requires vigilance Missing operations such as truncating or extending a file (ala POSIX ftruncate) Inconsistency between concrete implementations; e.g. stringstream has independent get/put positions whereas filestream does not Inconsistency between platform implementations; e.g. behavior of seeking pass the end of a file or usage of failbit/badbit on errors Don't need all the formatting facilities of stream or possibly even the buffering of streambuf streambuf error reporting (i.e. exceptions vs. returning an error indicator) is supposedly implementation-dependent in practice I like the simplified interface provided by the Boost.Iostreams Device concept, but it's provided as function templates rather than a polymorphic class. (There is a device class, but it's not polymorphic and is just an implementation helper class not necessarily used by the supplied device implementations.) I'm primarily using large disk files, but I really want polymorphism so I can easily substitute alternate implementations (e.g. use stringstream instead of fstream for unit tests) without all the complexity and compile-time coupling of deep template instantiation. Does anyone have any recommendations of a standard approach to this? It seems like a common situation, so I don't want to invent my own interfaces unnecessarily. As an example, something like java.nio.FileChannel seems ideal. My best solution so far is to put a thin polymorphic layer on top of Boost.Iostreams devices. For example: class my_istream { public: virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way) = 0; virtual std::streamsize read(char* s, std::streamsize n) = 0; virtual void close() = 0; }; template <class T> class boost_istream : public my_istream { public: boost_istream(const T& device) : m_device(device) { } virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way) { return boost::iostreams::seek(m_device, off, way); } virtual std::streamsize read(char* s, std::streamsize n) { return boost::iostreams::read(m_device, s, n); } virtual void close() { boost::iostreams::close(m_device); } private: T m_device; };

    Read the article

  • Is it possible to read infinity or NaN values using input streams?

    - by Drise
    I have some input to be read by a input filestream (for example): -365.269511 -0.356123 -Inf 0.000000 When I use std::ifstream mystream; to read from the file to some double d1 = -1, d2 = -1, d3 = -1, d4 = -1; (assume mystream has already been opened and the file is valid), mystream >> d1 >> d2 >> d3 >> d4; mystream is in the fail state. I would expect std::cout << d1 << " " << d2 << " " << d3 << " " << d4 << std::endl; to output -365.269511 -0.356123 -1 -1. I would want it to output -365.269511 -0.356123 -Inf 0 instead. This set of data was output using C++ streams. Why can't I do the reverse process (read in my output)? How can I get the functionality I seek? From MooingDuck: #include <iostream> #include <limits> using namespace std; int main() { double myd = std::numeric_limits<double>::infinity(); cout << myd << '\n'; cin >> myd; cout << cin.good() << ":" << myd << endl; return 0; } Input: inf Output: inf 0:inf See also: http://ideone.com/jVvei Also related to this problem is NaN parsing, even though I do not give examples for it.

    Read the article

  • Large File Download - Connection With Server Reset

    - by daveywc
    I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset. Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event. private void DownloadFile(string fname, bool forceDownload) { string path = MapPath(fname); string name = Path.GetFileName(path); string ext = Path.GetExtension(path); string type = ""; // set known types based on file extension if (ext != null) { switch (ext.ToLower()) { case ".mp3": type = "audio/mpeg"; break; case ".htm": case ".html": type = "text/HTML"; break; case ".txt": type = "text/plain"; break; case ".doc": case ".rtf": type = "Application/msword"; break; } } if (forceDownload) { Response.AppendHeader("content-disposition", "attachment; filename=" + name.Replace(" ", "_")); } if (type != "") { Response.ContentType = type; } else { Response.ContentType = "application/x-msdownload"; } System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } }

    Read the article

  • How Do you Declare a Dependancy Property in VB.Net 3.0

    - by discwiz
    My company is stuck on .Net 3.0. The task I am trying to tackle is simple, I need to bind the IsChecked property of the CheckBoxResolvesCEDAR to the CompletesCEDARWork in my Audio class. The more I read about this it appears that I have to declare CompletesCEDARWork as dependancy propert, but I can not find a good example of how this is done. I found this example, but when I pasted into my code I get an "is not defined" error for GetValue and I have not successfully figure out what MyCode is supposed to represent. Any help/examples would be greatly appreciated. Thanks Public Shared ReadOnly IsSpinningProperty As DependencyProperty = DependencyProperty.Register("IsSpinning", GetType(Boolean), GetType(MyCode)) Public Property IsSpinning() As Boolean Get Return CBool(GetValue(IsSpinningProperty)) End Get Set(ByVal value As Boolean) SetValue(IsSpinningProperty, value) End Set End Property Here is my slimed down Audio Class as it stands now. Imports System.Xml Imports System Imports System.IO Imports System.Collections.ObjectModel Imports System.ComponentModel Public Class Audio Private mXMLString As String Private mTarpID As Integer Private mStartTime As Date Private mEndTime As Date Private mAudioArray As Byte() Private mFileXMLInfo As IO.FileInfo Private mFileXMLStream As IO.FileStream Private mFileAudioInfo As IO.FileInfo Private mDisplayText As String Private mCompletesCEDARWork As Boolean Private Property CompletesCEDARWork() As Boolean Get Return mCompletesCEDARWork End Get Set(ByVal value As Boolean) mCompletesCEDARWork = value End Set End Property And here is my XML Datatemplate where I set the binding. <DataTemplate x:Key="UploadLayout" DataType="Audio"> <Border BorderBrush="LightGray" CornerRadius="8" BorderThickness="1" Padding="10" Margin="0,3,0,0"> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Path=DisplayText}"> </TextBlock> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <TextBlock Text="TARP ID" VerticalAlignment="Center"/> <ComboBox x:Name="ListBoxTarpIDs" ItemsSource="{Binding Path=TarpIds}" SelectedValue="{Binding Path=TarpID}" BorderBrush="Transparent" Background="Transparent" > </ComboBox> </StackPanel> <CheckBox x:Name="CheckBoxResolvesCEDAR" Content="Resolves CEDAR Work" IsChecked="{Binding ElementName=Audio,Path=CompletesCEDARWork,Mode=TwoWay}"/> </StackPanel> </Border> </DataTemplate>

    Read the article

  • representing an XML config file with an IXmlSerializable class

    - by Sarah Vessels
    I'm writing in C# and trying to represent an XML config file through an IXmlSerializable class. I'm unsure how to represent the nested elements in my config file, though, such as logLevel: <?xml version="1.0" encoding="utf-8" ?> <configuration> <logging> <logLevel>Error</logLevel> </logging> <credentials> <user>user123</user> <host>localhost</host> <password>pass123</password> </credentials> <credentials> <user>user456</user> <host>my.other.domain.com</host> <password>pass456</password> </credentials> </configuration> There is an enum called LogLevel that represents all the possible values for the logLevel tag. The tags within credentials should all come out as strings. In my class, called DLLConfigFile, I had the following: [XmlElement(ElementName="logLevel", DataType="LogLevel")] public LogLevel LogLevel; However, this isn't going to work because <logLevel> isn't within the root node of the XML file, it's one node deeper in <logging>. How do I go about doing this? As for the <credentials> nodes, my guess is I will need a second class, say CredentialsSection, and have a property such as the following: [XmlElement(ElementName="credentials", DataType="CredentialsSection")] public CredentialsSection[] AllCredentials; Edit: okay, I tried Robert Love's suggestion and created a LoggingSection class. However, my test fails: var xs = new XmlSerializer(typeof(DLLConfigFile)); using (var stream = new FileStream(_configPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var streamReader = new StreamReader(stream)) { XmlReader reader = new XmlTextReader(streamReader); var file = (DLLConfigFile)xs.Deserialize(reader); Assert.IsNotNull(file); LoggingSection logging = file.Logging; Assert.IsNotNull(logging); // fails here LogLevel logLevel = logging.LogLevel; Assert.IsNotNull(logLevel); Assert.AreEqual(EXPECTED_LOG_LEVEL, logLevel); } } The config file I'm testing with definitely has <logging>. Here's what the classes look like: [Serializable] [XmlRoot("logging")] public class LoggingSection : IXmlSerializable { public XmlSchema GetSchema() { return null; } [XmlElement(ElementName="logLevel", DataType="LogLevel")] public LogLevel LogLevel; public void ReadXml(XmlReader reader) { LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), reader.ReadString()); } public void WriteXml(XmlWriter writer) { writer.WriteString(Enum.GetName(typeof(LogLevel), LogLevel)); } } [Serializable] [XmlRoot("configuration")] public class DLLConfigFile : IXmlSerializable { [XmlElement(ElementName="logging", DataType="LoggingSection")] public LoggingSection Logging; }

    Read the article

  • BNF – how to read syntax?

    - by Piotr Rodak
    A few days ago I read post of Jen McCown (blog) about her idea of blogging about random articles from Books Online. I think this is a great idea, even if Jen says that it’s not exciting or sexy. I noticed that many of the questions that appear on forums and other media arise from pure fact that people asking questions didn’t bother to read and understand the manual – Books Online. Jen came up with a brilliant, concise acronym that describes very well the category of posts about Books Online – RTFM365. I take liberty of tagging this post with the same acronym. I often come across questions of type – ‘Hey, i am trying to create a table, but I am getting an error’. The error often says that the syntax is invalid. 1 CREATE TABLE dbo.Employees 2 (guid uniqueidentifier CONSTRAINT DEFAULT Guid_Default NEWSEQUENTIALID() ROWGUIDCOL, 3 Employee_Name varchar(60) 4 CONSTRAINT Guid_PK PRIMARY KEY (guid) ); 5 The answer is usually(1), ‘Ok, let me check it out.. Ah yes – you have to put name of the DEFAULT constraint before the type of constraint: 1 CREATE TABLE dbo.Employees 2 (guid uniqueidentifier CONSTRAINT Guid_Default DEFAULT NEWSEQUENTIALID() ROWGUIDCOL, 3 Employee_Name varchar(60) 4 CONSTRAINT Guid_PK PRIMARY KEY (guid) ); Why many people stumble on syntax errors? Is the syntax poorly documented? No, the issue is, that correct syntax of the CREATE TABLE statement is documented very well in Books Online and is.. intimidating. Many people can be taken aback by the rather complex block of code that describes all intricacies of the statement. However, I don’t know better way of defining syntax of the statement or command. The notation that is used to describe syntax in Books Online is a form of Backus-Naur notatiion, called BNF for short sometimes. This is a notation that was invented around 50 years ago, and some say that even earlier, around 400 BC – would you believe? Originally it was used to define syntax of, rather ancient now, ALGOL programming language (in 1950’s, not in ancient India). If you look closer at the definition of the BNF, it turns out that the principles of this syntax are pretty simple. Here are a few bullet points: italic_text is a placeholder for your identifier <italic_text_in_angle_brackets> is a definition which is described further. [everything in square brackets] is optional {everything in curly brackets} is obligatory everything | separated | by | operator is an alternative ::= “assigns” definition to an identifier Yes, it looks like these six simple points give you the key to understand even the most complicated syntax definitions in Books Online. Books Online contain an article about syntax conventions – have you ever read it? Let’s have a look at fragment of the CREATE TABLE statement: 1 CREATE TABLE 2 [ database_name . [ schema_name ] . | schema_name . ] table_name 3 ( { <column_definition> | <computed_column_definition> 4 | <column_set_definition> } 5 [ <table_constraint> ] [ ,...n ] ) 6 [ ON { partition_scheme_name ( partition_column_name ) | filegroup 7 | "default" } ] 8 [ { TEXTIMAGE_ON { filegroup | "default" } ] 9 [ FILESTREAM_ON { partition_scheme_name | filegroup 10 | "default" } ] 11 [ WITH ( <table_option> [ ,...n ] ) ] 12 [ ; ] Let’s look at line 2 of the above snippet: This line uses rules 3 and 5 from the list. So you know that you can create table which has specified one of the following. just name – table will be created in default user schema schema name and table name – table will be created in specified schema database name, schema name and table name – table will be created in specified database, in specified schema database name, .., table name – table will be created in specified database, in default schema of the user. Note that this single line of the notation describes each of the naming schemes in deterministic way. The ‘optionality’ of the schema_name element is nested within database_name.. section. You can use either database_name and optional schema name, or just schema name – this is specified by the pipe character ‘|’. The error that user gets with execution of the first script fragment in this post is as follows: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'DEFAULT'. Ok, let’s have a look how to find out the correct syntax. Line number 3 of the BNF fragment above contains reference to <column_definition>. Since column_definition is in angle brackets, we know that this is a reference to notion described further in the code. And indeed, the very next fragment of BNF contains syntax of the column definition. 1 <column_definition> ::= 2 column_name <data_type> 3 [ FILESTREAM ] 4 [ COLLATE collation_name ] 5 [ NULL | NOT NULL ] 6 [ 7 [ CONSTRAINT constraint_name ] DEFAULT constant_expression ] 8 | [ IDENTITY [ ( seed ,increment ) ] [ NOT FOR REPLICATION ] 9 ] 10 [ ROWGUIDCOL ] [ <column_constraint> [ ...n ] ] 11 [ SPARSE ] Look at line 7 in the above fragment. It says, that the column can have a DEFAULT constraint which, if you want to name it, has to be prepended with [CONSTRAINT constraint_name] sequence. The name of the constraint is optional, but I strongly recommend you to make the effort of coming up with some meaningful name yourself. So the correct syntax of the CREATE TABLE statement from the beginning of the article is like this: 1 CREATE TABLE dbo.Employees 2 (guid uniqueidentifier CONSTRAINT Guid_Default DEFAULT NEWSEQUENTIALID() ROWGUIDCOL, 3 Employee_Name varchar(60) 4 CONSTRAINT Guid_PK PRIMARY KEY (guid) ); That is practically everything you should know about BNF. I encourage you to study the syntax definitions for various statements and commands in Books Online, you can find really interesting things hidden there. Technorati Tags: SQL Server,t-sql,BNF,syntax   (1) No, my answer usually is a question – ‘What error message? What does it say?’. You’d be surprised to know how many people think I can go through time and space and look at their screen at the moment they received the error.

    Read the article

  • SQL SERVER – Introduction to SQL Server 2014 In-Memory OLTP

    - by Pinal Dave
    In SQL Server 2014 Microsoft has introduced a new database engine component called In-Memory OLTP aka project “Hekaton” which is fully integrated into the SQL Server Database Engine. It is optimized for OLTP workloads accessing memory resident data. In-memory OLTP helps us create memory optimized tables which in turn offer significant performance improvement for our typical OLTP workload. The main objective of memory optimized table is to ensure that highly transactional tables could live in memory and remain in memory forever without even losing out a single record. The most significant part is that it still supports majority of our Transact-SQL statement. Transact-SQL stored procedures can be compiled to machine code for further performance improvements on memory-optimized tables. This engine is designed to ensure higher concurrency and minimal blocking. In-Memory OLTP alleviates the issue of locking, using a new type of multi-version optimistic concurrency control. It also substantially reduces waiting for log writes by generating far less log data and needing fewer log writes. Points to remember Memory-optimized tables refer to tables using the new data structures and key words added as part of In-Memory OLTP. Disk-based tables refer to your normal tables which we used to create in SQL Server since its inception. These tables use a fixed size 8 KB pages that need to be read from and written to disk as a unit. Natively compiled stored procedures refer to an object Type which is new and is supported by in-memory OLTP engine which convert it into machine code, which can further improve the data access performance for memory –optimized tables. Natively compiled stored procedures can only reference memory-optimized tables, they can’t be used to reference any disk –based table. Interpreted Transact-SQL stored procedures, which is what SQL Server has always used. Cross-container transactions refer to transactions that reference both memory-optimized tables and disk-based tables. Interop refers to interpreted Transact-SQL that references memory-optimized tables. Using In-Memory OLTP In-Memory OLTP engine has been available as part of SQL Server 2014 since June 2013 CTPs. Installation of In-Memory OLTP is part of the SQL Server setup application. The In-Memory OLTP components can only be installed with a 64-bit edition of SQL Server 2014 hence they are not available with 32-bit editions. Creating Databases Any database that will store memory-optimized tables must have a MEMORY_OPTIMIZED_DATA filegroup. This filegroup is specifically designed to store the checkpoint files needed by SQL Server to recover the memory-optimized tables, and although the syntax for creating the filegroup is almost the same as for creating a regular filestream filegroup, it must also specify the option CONTAINS MEMORY_OPTIMIZED_DATA. Here is an example of a CREATE DATABASE statement for a database that can support memory-optimized tables: CREATE DATABASE InMemoryDB ON PRIMARY(NAME = [InMemoryDB_data], FILENAME = 'D:\data\InMemoryDB_data.mdf', size=500MB), FILEGROUP [SampleDB_mod_fg] CONTAINS MEMORY_OPTIMIZED_DATA (NAME = [InMemoryDB_mod_dir], FILENAME = 'S:\data\InMemoryDB_mod_dir'), (NAME = [InMemoryDB_mod_dir], FILENAME = 'R:\data\InMemoryDB_mod_dir') LOG ON (name = [SampleDB_log], Filename='L:\log\InMemoryDB_log.ldf', size=500MB) COLLATE Latin1_General_100_BIN2; Above example code creates files on three different drives (D:  S: and R:) for the data files and in memory storage so if you would like to run this code kindly change the drive and folder locations as per your convenience. Also notice that binary collation was specified as Windows (non-SQL). BIN2 collation is the only collation support at this point for any indexes on memory optimized tables. It is also possible to add a MEMORY_OPTIMIZED_DATA file group to an existing database, use the below command to achieve the same. ALTER DATABASE AdventureWorks2012 ADD FILEGROUP hekaton_mod CONTAINS MEMORY_OPTIMIZED_DATA; GO ALTER DATABASE AdventureWorks2012 ADD FILE (NAME='hekaton_mod', FILENAME='S:\data\hekaton_mod') TO FILEGROUP hekaton_mod; GO Creating Tables There is no major syntactical difference between creating a disk based table or a memory –optimized table but yes there are a few restrictions and a few new essential extensions. Essentially any memory-optimized table should use the MEMORY_OPTIMIZED = ON clause as shown in the Create Table query example. DURABILITY clause (SCHEMA_AND_DATA or SCHEMA_ONLY) Memory-optimized table should always be defined with a DURABILITY value which can be either SCHEMA_AND_DATA or  SCHEMA_ONLY the former being the default. A memory-optimized table defined with DURABILITY=SCHEMA_ONLY will not persist the data to disk which means the data durability is compromised whereas DURABILITY= SCHEMA_AND_DATA ensures that data is also persisted along with the schema. Indexing Memory Optimized Table A memory-optimized table must always have an index for all tables created with DURABILITY= SCHEMA_AND_DATA and this can be achieved by declaring a PRIMARY KEY Constraint at the time of creating a table. The following example shows a PRIMARY KEY index created as a HASH index, for which a bucket count must also be specified. CREATE TABLE Mem_Table ( [Name] VARCHAR(32) NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000), [City] VARCHAR(32) NULL, [State_Province] VARCHAR(32) NULL, [LastModified] DATETIME NOT NULL, ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA); Now as you can see in the above query example we have used the clause MEMORY_OPTIMIZED = ON to make sure that it is considered as a memory optimized table and not just a normal table and also used the DURABILITY Clause= SCHEMA_AND_DATA which means it will persist data along with metadata and also you can notice this table has a PRIMARY KEY mentioned upfront which is also a mandatory clause for memory-optimized tables. We will talk more about HASH Indexes and BUCKET_COUNT in later articles on this topic which will be focusing more on Row and Index storage on Memory-Optimized tables. So stay tuned for that as well. Now as we covered the basics of Memory Optimized tables and understood the key things to remember while using memory optimized tables, let’s explore more using examples to understand the Performance gains using memory-optimized tables. I will be using the database which i created earlier in this article i.e. InMemoryDB in the below Demo Exercise. USE InMemoryDB GO -- Creating a disk based table CREATE TABLE dbo.Disktable ( Id INT IDENTITY, Name CHAR(40) ) GO CREATE NONCLUSTERED INDEX IX_ID ON dbo.Disktable (Id) GO -- Creating a memory optimized table with similar structure and DURABILITY = SCHEMA_AND_DATA CREATE TABLE dbo.Memorytable_durable ( Id INT NOT NULL PRIMARY KEY NONCLUSTERED Hash WITH (bucket_count =1000000), Name CHAR(40) ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA) GO -- Creating an another memory optimized table with similar structure but DURABILITY = SCHEMA_Only CREATE TABLE dbo.Memorytable_nondurable ( Id INT NOT NULL PRIMARY KEY NONCLUSTERED Hash WITH (bucket_count =1000000), Name CHAR(40) ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_only) GO -- Now insert 100000 records in dbo.Disktable and observe the Time Taken DECLARE @i_t bigint SET @i_t =1 WHILE @i_t<= 100000 BEGIN INSERT INTO dbo.Disktable(Name) VALUES('sachin' + CONVERT(VARCHAR,@i_t)) SET @i_t+=1 END -- Do the same inserts for Memory table dbo.Memorytable_durable and observe the Time Taken DECLARE @i_t bigint SET @i_t =1 WHILE @i_t<= 100000 BEGIN INSERT INTO dbo.Memorytable_durable VALUES(@i_t, 'sachin' + CONVERT(VARCHAR,@i_t)) SET @i_t+=1 END -- Now finally do the same inserts for Memory table dbo.Memorytable_nondurable and observe the Time Taken DECLARE @i_t bigint SET @i_t =1 WHILE @i_t<= 100000 BEGIN INSERT INTO dbo.Memorytable_nondurable VALUES(@i_t, 'sachin' + CONVERT(VARCHAR,@i_t)) SET @i_t+=1 END The above 3 Inserts took 1.20 minutes, 54 secs, and 2 secs respectively to insert 100000 records on my machine with 8 Gb RAM. This proves the point that memory-optimized tables can definitely help businesses achieve better performance for their highly transactional business table and memory- optimized tables with Durability SCHEMA_ONLY is even faster as it does not bother persisting its data to disk which makes it supremely fast. Koenig Solutions is one of the few organizations which offer IT training on SQL Server 2014 and all its updates. Now, I leave the decision on using memory_Optimized tables on you, I hope you like this article and it helped you understand  the fundamentals of IN-Memory OLTP . Reference: Pinal Dave (http://blog.sqlauthority.com)Filed under: PostADay, SQL, SQL Authority, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, T SQL Tagged: Koenig

    Read the article

  • CodePlex Daily Summary for Saturday, March 27, 2010

    CodePlex Daily Summary for Saturday, March 27, 2010New ProjectsAlter gear SQL index Management: SQL Index management displays a list of indexes available for the chosen database and allows you to select an individual / group of indexes to be r...ASP League Ladder System: An ASP ladder / league system for online gaming league or real life leagues also.Augmented Reality Strategy Simulator: Augmented Reality Strategy Simulator is a software suite to promote computer aided strategy planning. Sports team can visualize their strategy usin...Boo syntax highlighting for Visual Studio 2010: Simple syntax hightlighting VSX add-in for Boo language in Visual Studio 2010.easySan: easySan zur einfachen Mitgliedsverwaltung im BRKFsUnit: FsUnit makes unit-testing with F# more enjoyable. It adds a special syntax to your favorite .NET testing framework.Laughing Dog XNA Framework: Laughing Dog is a simple to use, component based 2D framework for XNA game development. At present it is very early in development and as such is f...miniTodo: WPFでMVVMの練習にてきとうに作ったTODOアプリ 実用は無理です。My Common Library on .NET with CSharp: My Common Library on .NET with CSharp, it conclude database assecc, encrypt string, data caching, StringUtility, thank you for your view.Native code wrapping using c# : fsutil sparse commands: Ever thought about creating HUGE FILES for future use but felt bad for the wasted memory? Well, SPARSE FILES are the ANSWER! This FSUTIL SPARSE CO...Open SOA Platform: A centralized system for administering applications throught a SOA Enterprise Service Bus: Runtime environment (PROD, DEV, ...) , application and s...P-DBMS: Network and Database ProjectPraiseSight: PraiseSight is supposed to become a practical tool for churches to catalog an present their songs, lyrics and presentations on a beamer. The soluti...Pretty Good Frontend: Pretty Good Frontend is a sample frontend for ConfigMgr (SCCM) 2007 and MDT 2010 Zero Touch. S3Appender (Appender for Log4Net that Uses Amazon S3 For Storing Log Files): The S3Appender is a log4net appender that stores log events in either a MemoryStream or FileStream and sends them to S3 based on time intervals and...sEmit: sEmit (sms emitter) is an application written in C# which was built to send text messages. The project was founded in May 2009 by cansik. It works ...Silverlight RIA Tools: A tool set that generates a full RIA Solutions in Silverlightthommo cannon: Cannon for shooting down ThommosTianjin Polytechnic University Online Judge: Online Judge System Built on Microsoft technologies. Vision & Scope: A distributed OJ Solution on Windows and Cloud. Technologies used or planed...Tinare: Tinare is an byte encryption and decryption alogrithm. The input key is a string password.TinyPlug: Small Plugin Manager, written in C# Allows a project to define supported interfaces, and at runtime add plugins which support (inherit) these in...Utility niconv helps to convert text from one encoding to another: .NET implementation of GUN iconv console converter utility. The niconv program converts text from one encoding to another encoding. In the future r...WareFeed - Software Business Analytics: WareFeed is a simple but effective Software Business Analytics tool written in PHP and compatible others languages such as .NET, Java or Python. It...Y36API1: Semestralni projekt na Y36APINew ReleasesAlter gear SQL index Management: Setup 1.0.0: setup for first alpha releaseASP League Ladder System: ASPLeagueRelease_0_4_1: Release v 0.41Augmented Reality Strategy Simulator: Augmented Reality Strategy Simulator: Version 1.0 InstallerAutoAudit: AutoAudit 1.10e: Version 1.10e will be the final iteration of version 1 development. Version 2 will begin adding switches and options. Pleae email your suggestio...Boo syntax highlighting for Visual Studio 2010: Boo syntax VS 2010 - alpha: First release TODO: Multiline comments!Chargify.NET: Chargify.NET 0.6: Updated library, using Metered Components and updated Product information.Composer: V1.0.326.1000 Alpha: Initial Alpha release. Should be stable, with minor issues.CoNatural Components: CoNatural Components 1.6: Code fixes: Created helper classes to generate source code for type mapper/materializer. Fixed issue in optimized type materializer when loading ...CRM External View: 1.2: New Features in v1.2 release Password protected views. No more using Web Data Access role from v1. Filtering capabilities Caching for performan...Designit Video Embed Package: Release 1.1.0 beta1: You can now either have the video embeded directly in the template or have a preview in template that opens the video in a lightbox window.FsUnit: FsUnit 0.9.0 for NUnit: This release is for F# 2.0 and NUnit 2.5+.Laughing Dog XNA Framework: Laughing Dog 0.0.1: Laughing Dog - Alpla - v 0.0.1 First released version of the Laughing Dog framework.LiveUpload to Facebook: LiveUpload to Facebook 3.2: Version 3.2Become a fan on Facebook! Features Quickly and easily upload your photos and videos to Facebook, including any people tags added in Win...MapWindow6: MapWindow 6.0 msi March 26: This version adds the Join feature for creating a new "featureset" with attributes that are joined with attributes from a Excel data label named 'D...Mobile Broadband Logging Monitor: Mobile Broadband Logging Monitor 1.2.2: This edition supports: Newer and older editions of Birdstep Technology's EasyConnect HUAWEI Mobile Partner MWConn User defined location for s...Multiplayer Quiz: Release 1_6_351_0: A beta release of the next version. Please leave any errors in discussions or comments.Native code wrapping using c# : fsutil sparse commands: Fsutil sparse file native code - c sharp wrapper: Project Description A C# code wrapping a native code-Sparse files1 The code is about SPARSE files- the abillity to create huge files (for future us...Nice Libraries: 1.30 build 50325.01: Release 1.30 build 50325.01Pretty Good Frontend: Pretty Good Frontend binaries v1.0: This is the first public release of the Pretty Good Frontend binariesPylor: Pylor 0.1 alpha: This is the very first published version. I hope I can put a sample project soon.Quick Performance Monitor: Version 1.1 refresh: There was a typo or two in the sample batch file. Corrected now.Rapidshare Episode Downloader: RED v0.8.3: 0.8.1 introduced the ability to advance to the next episode. In 0.8.2 a bug was found that if episode number is less then 10, then the preceding 0...RapidWebDev - .NET Enterprise Software Development Infrastructure: RapidWebDev 1.52: RapidWebDev is an infrastructure helps to develop enterprise software solutions in Microsoft .NET easily and productively. This is the release vers...thommo cannon: game: gamethommo cannon: setup: setupthommo cannon: test: testTinare: Tinare DLL: Tinare DLL is a dynamic-link library written in C# which provides the functions to encrypt and decrypt a byte stream with tinare.WeatherBar: WeatherBar 2.1 [No Installation]: Minor changes to release 2.0 (http://weatherbar.codeplex.com/releases/view/42490). Fixed the bug that caused an exception to be thrown if the user...Most Popular ProjectsMetaSharpRawrWBFS ManagerASP.NET Ajax LibrarySilverlight ToolkitMicrosoft SQL Server Product Samples: DatabaseAJAX Control ToolkitLiveUpload to FacebookWindows Presentation Foundation (WPF)ASP.NETMost Active ProjectsRawrjQuery Library for SharePoint Web ServicesBlogEngine.NETMicrosoft Biology FoundationFarseer Physics Enginepatterns & practices: Composite WPF and SilverlightLINQ to TwitterTable2ClassFluent Ribbon Control SuiteNB_Store - Free DotNetNuke Ecommerce Catalog Module

    Read the article

  • Updating a SharePoint master page via a solution (WSP)

    - by Kelly Jones
    In my last blog post, I wrote how to deploy a SharePoint theme using Features and a solution package.  As promised in that post, here is how to update an already deployed master page. There are several ways to update a master page in SharePoint.  You could upload a new version to the master page gallery, or you could upload a new master page to the gallery, and then set the site to use this new page.  Manually uploading your master page to the master page gallery might be the best option, depending on your environment.  For my client, I did these steps in code, which is what they preferred. (Image courtesy of: http://www.joiningdots.net/blog/2007/08/sharepoint-and-quick-launch.html ) Before you decide which method you need to use, take a look at your existing pages.  Are they using the SharePoint dynamic token or the static token for the master page reference?  The wha, huh? SO, there are four ways to tell an .aspx page hosted in SharePoint which master page it should use: “~masterurl/default.master” – tells the page to use the default.master property of the site “~masterurl/custom.master” – tells the page to use the custom.master property of the site “~site/default.master” – tells the page to use the file named “default.master” in the site’s master page gallery “~sitecollection/default.master” – tells the page to use the file named “default.master” in the site collection’s master page gallery For more information about these tokens, take a look at this article on MSDN. Once you determine which token your existing pages are pointed to, then you know which file you need to update.  So, if the ~masterurl tokens are used, then you upload a new master page, either replacing the existing one or adding another one to the gallery.  If you’ve uploaded a new file with a new name, you’ll just need to set it as the master page either through the UI (MOSS only) or through code (MOSS or WSS Feature receiver code – or using SharePoint Designer). If the ~site or ~sitecollection tokens were used, then you’re limited to either replacing the existing master page, or editing all of your existing pages to point to another master page.  In most cases, it probably makes sense to just replace the master page. For my project, I’m working with WSS and the existing pages are set to the ~sitecollection token.  Based on this, I decided to just upload a new version of the existing master page (and not modify the dozens of existing pages). Also, since my client prefers Features and solutions, I created a master page Feature and a corresponding Feature Receiver.  For information on creating the elements and feature files, check out this post: http://sharepointmagazine.net/technical/development/deploying-the-master-page . This works fine, unless you are overwriting an existing master page, which was my case.  You’ll run into errors because the master page file needs to be checked out, replaced, and then checked in.  I wrote code in my Feature Activated event handler to accomplish these steps. Here are the steps necessary in code: Get the file name from the elements file of the Feature Check out the file from the master page gallery Upload the file to the master page gallery Check in the file to the master page gallery Here’s the code in my Feature Receiver: 1: public override void FeatureActivated(SPFeatureReceiverProperties properties) 2: { 3: try 4: { 5:   6: SPElementDefinitionCollection col = properties.Definition.GetElementDefinitions(System.Globalization.CultureInfo.CurrentCulture); 7:   8: using (SPWeb curweb = GetCurWeb(properties)) 9: { 10: foreach (SPElementDefinition ele in col) 11: { 12: if (string.Compare(ele.ElementType, "Module", true) == 0) 13: { 14: // <Module Name="DefaultMasterPage" List="116" Url="_catalogs/masterpage" RootWebOnly="FALSE"> 15: // <File Url="myMaster.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" 16: // Path="MasterPages/myMaster.master" /> 17: // </Module> 18: string Url = ele.XmlDefinition.Attributes["Url"].Value; 19: foreach (System.Xml.XmlNode file in ele.XmlDefinition.ChildNodes) 20: { 21: string Url2 = file.Attributes["Url"].Value; 22: string Path = file.Attributes["Path"].Value; 23: string fileType = file.Attributes["Type"].Value; 24:   25: if (string.Compare(fileType, "GhostableInLibrary", true) == 0) 26: { 27: //Check out file in document library 28: SPFile existingFile = curweb.GetFile(Url + "/" + Url2); 29:   30: if (existingFile != null) 31: { 32: if (existingFile.CheckOutStatus != SPFile.SPCheckOutStatus.None) 33: { 34: throw new Exception("The master page file is already checked out. Please make sure the master page file is checked in, before activating this feature."); 35: } 36: else 37: { 38: existingFile.CheckOut(); 39: existingFile.Update(); 40: } 41: } 42:   43: //Upload file to document library 44: string filePath = System.IO.Path.Combine(properties.Definition.RootDirectory, Path); 45: string fileName = System.IO.Path.GetFileName(filePath); 46: char slash = Convert.ToChar("/"); 47: string[] folders = existingFile.ParentFolder.Url.Split(slash); 48:   49: if (folders.Length > 2) 50: { 51: Logger.logMessage("More than two folders were detected in the library path for the master page. Only two are supported.", 52: Logger.LogEntryType.Information); //custom logging component 53: } 54:   55: SPFolder myLibrary = curweb.Folders[folders[0]].SubFolders[folders[1]]; 56:   57: FileStream fs = File.OpenRead(filePath); 58:   59: SPFile newFile = myLibrary.Files.Add(fileName, fs, true); 60:   61: myLibrary.Update(); 62: newFile.CheckIn("Updated by Feature", SPCheckinType.MajorCheckIn); 63: newFile.Update(); 64: } 65: } 66: } 67: } 68: } 69: } 70: catch (Exception ex) 71: { 72: string msg = "Error occurred during feature activation"; 73: Logger.logException(ex, msg, ""); 74: } 75:   76: } 77:   78: /// <summary> 79: /// Using a Feature's properties, get a reference to the Current Web 80: /// </summary> 81: /// <param name="properties"></param> 82: public SPWeb GetCurWeb(SPFeatureReceiverProperties properties) 83: { 84: SPWeb curweb; 85:   86: //Check if the parent of the web is a site or a web 87: if (properties != null && properties.Feature.Parent.GetType().ToString() == "Microsoft.SharePoint.SPWeb") 88: { 89:   90: //Get web from parent 91: curweb = (SPWeb)properties.Feature.Parent; 92: 93: } 94: else 95: { 96: //Get web from Site 97: using (SPSite cursite = (SPSite)properties.Feature.Parent) 98: { 99: curweb = (SPWeb)cursite.OpenWeb(); 100: } 101: } 102:   103: return curweb; 104: } This did the trick.  It allowed me to update my existing master page, through an easily repeatable process (which is great when you are working with more than one environment and what to do things like TEST it!).  I did run into what I would classify as a strange issue with one of my subsites, but that’s the topic for another blog post.

    Read the article

  • Full-text Indexing Books Online

    - by Most Valuable Yak (Rob Volk)
    While preparing for a recent SQL Saturday presentation, I was struck by a crazy idea (shocking, I know): Could someone import the content of SQL Server Books Online into a database and apply full-text indexing to it?  The answer is yes, and it's really quite easy to do. The first step is finding the installed help files.  If you have SQL Server 2012, BOL is installed under the Microsoft Help Library.  You can find the install location by opening SQL Server Books Online and clicking the gear icon for the Help Library Manager.  When the new window pops up click the Settings link, you'll get the following: You'll see the path under Library Location. Once you navigate to that path you'll have to drill down a little further, to C:\ProgramData\Microsoft\HelpLibrary\content\Microsoft\store.  This is where the help file content is kept if you downloaded it for offline use. Depending on which products you've downloaded help for, you may see a few hundred files.  Fortunately they're named well and you can easily find the "SQL_Server_Denali_Books_Online_" files.  We are interested in the .MSHC files only, and can skip the Installation and Developer Reference files. Despite the .MHSC extension, these files are compressed with the standard Zip format, so your favorite archive utility (WinZip, 7Zip, WinRar, etc.) can open them.  When you do, you'll see a few thousand files in the archive.  We are only interested in the .htm files, but there's no harm in extracting all of them to a folder.  7zip provides a command-line utility and the following will extract to a D:\SQLHelp folder previously created: 7z e –oD:\SQLHelp "C:\ProgramData\Microsoft\HelpLibrary\content\Microsoft\store\SQL_Server_Denali_Books_Online_B780_SQL_110_en-us_1.2.mshc" *.htm Well that's great Rob, but how do I put all those files into a full-text index? I'll tell you in a second, but first we have to set up a few things on the database side.  I'll be using a database named Explore (you can certainly change that) and the following setup is a fragment of the script I used in my presentation: USE Explore; GO CREATE SCHEMA help AUTHORIZATION dbo; GO -- Create default fulltext catalog for later FT indexes CREATE FULLTEXT CATALOG FTC AS DEFAULT; GO CREATE TABLE help.files(file_id int not null IDENTITY(1,1) CONSTRAINT PK_help_files PRIMARY KEY, path varchar(256) not null CONSTRAINT UNQ_help_files_path UNIQUE, doc_type varchar(6) DEFAULT('.xml'), content varbinary(max) not null); CREATE FULLTEXT INDEX ON help.files(content TYPE COLUMN doc_type LANGUAGE 1033) KEY INDEX PK_help_files; This will give you a table, default full-text catalog, and full-text index on that table for the content you're going to insert.  I'll be using the command line again for this, it's the easiest method I know: for %a in (D:\SQLHelp\*.htm) do sqlcmd -S. -E -d Explore -Q"set nocount on;insert help.files(path,content) select '%a', cast(c as varbinary(max)) from openrowset(bulk '%a', SINGLE_CLOB) as c(c)" You'll need to copy and run that as one line in a command prompt.  I'll explain what this does while you run it and watch several thousand files get imported: The "for" command allows you to loop over a collection of items.  In this case we want all the .htm files in the D:\SQLHelp folder.  For each file it finds, it will assign the full path and file name to the %a variable.  In the "do" clause, we'll specify another command to be run for each iteration of the loop.  I make a call to "sqlcmd" in order to run a SQL statement.  I pass in the name of the server (-S.), where "." represents the local default instance. I specify -d Explore as the database, and -E for trusted connection.  I then use -Q to run a query that I enclose in double quotes. The query uses OPENROWSET(BULK…SINGLE_CLOB) to open the file as a data source, and to treat it as a single character large object.  In order for full-text indexing to work properly, I have to convert the text content to varbinary. I then INSERT these contents along with the full path of the file into the help.files table created earlier.  This process continues for each file in the folder, creating one new row in the table. And that's it! 5 SQL Statements and 2 command line statements to unzip and import SQL Server Books Online!  In case you're wondering why I didn't use FILESTREAM or FILETABLE, it's simply because I haven't learned them…yet. I may return to this blog after I figure that out and update it with the steps to do so.  I believe that will make it even easier. In the spirit of exploration, I'll leave you to work on some fulltext queries of this content.  I also recommend playing around with the sys.dm_fts_xxxx DMVs (I particularly like sys.dm_fts_index_keywords, it's pretty interesting).  There are additional example queries in the download material for my presentation linked above. Many thanks to Kevin Boles (t) for his advice on (re)checking the content of the help files.  Don't let that .htm extension fool you! The 2012 help files are actually XML, and you'd need to specify '.xml' in your document type column in order to extract the full-text keywords.  (You probably noticed this in the default definition for the doc_type column.)  You can query sys.fulltext_document_types to get a complete list of the types that can be full-text indexed. I also need to thank Hilary Cotter for giving me the original idea. I believe he used MSDN content in a full-text index for an article from waaaaaaaaaaay back, that I can't find now, and had forgotten about until just a few days ago.  He is also co-author of Pro Full-Text Search in SQL Server 2008, which I highly recommend.  He also has some FTS articles on Simple Talk: http://www.simple-talk.com/sql/learn-sql-server/sql-server-full-text-search-language-features/ http://www.simple-talk.com/sql/learn-sql-server/sql-server-full-text-search-language-features,-part-2/

    Read the article

  • Using Apache FOP from .NET level

    - by Lukasz Kurylo
    In one of my previous posts I was talking about FO.NET which I was using to generate a pdf documents from XSL-FO. FO.NET is one of the .NET ports of Apache FOP. Unfortunatelly it is no longer maintained. I known it when I decidec to use it, because there is a lack of available (free) choices for .NET to render a pdf form XSL-FO. I hoped in this implementation I will find all I need to create a pdf file with my really simple requirements. FO.NET is a port from some old version of Apache FOP and I found really quickly that there is a lack of some features that I needed, like dotted borders, double borders or support for margins. So I started to looking for some alternatives. I didn’t try the NFOP, another port of Apache FOP, because I found something I think much more better, the IKVM.NET project.   IKVM.NET it is not a pdf renderer. So what it is? From the project site:   IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. It includes the following components: a Java Virtual Machine implemented in .NET a .NET implementation of the Java class libraries tools that enable Java and .NET interoperability   In the simplest form IKVM.NET allows to use a Java code library in the C# code and vice versa.   I tried to use an Apache FOP, the best I think open source pdf –> XSL-FO renderer written in Java from my project written in C# using an IKVM.NET and it work like a charm. In the rest of the post I want to show, how to prepare a .NET *.dll class library from Apache FOP *.jar’s with IKVM.NET and generate a simple Hello world pdf document.   To start playing with IKVM.NET and Apache FOP we need to download their packages: IKVM.NET Apache FOP and then unpack them.   From the FOP directory copy all the *.jar’s files from lib and build catalogs to some location, e.g. d:\fop. Second step is to build the *.dll library from these files. On the console execute the following comand:   ikvmc –target:library –out:d:\fop\fop.dll –recurse:d:\fop   The ikvmc is located in the bin subdirectory where you unpacked the IKVM.NET. You must execute this command from this catalog, add this path to the global variable PATH or specify the full path to the bin subdirectory.   In no error occurred during this process, the fop.dll library should be created. Right now we can create a simple project to test if we can create a pdf file.   So let’s create a simple console project application and add reference to the fop.dll and the IKVM dll’s: IKVM.OpenJDK.Core and IKVM.OpenJDK.XML.API.   Full code to generate a pdf file from XSL-FO template:   static void Main(string[] args)         {             //initialize the Apache FOP             FopFactory fopFactory = FopFactory.newInstance();               //in this stream we will get the generated pdf file             OutputStream o = new DotNetOutputMemoryStream();             try             {                 Fop fop = fopFactory.newFop("application/pdf", o);                 TransformerFactory factory = TransformerFactory.newInstance();                 Transformer transformer = factory.newTransformer();                   //read the template from disc                 Source src = new StreamSource(new File("HelloWorld.fo"));                 Result res = new SAXResult(fop.getDefaultHandler());                 transformer.transform(src, res);             }             finally             {                 o.close();             }             using (System.IO.FileStream fs = System.IO.File.Create("HelloWorld.pdf"))             {                 //write from the .NET MemoryStream stream to disc the generated pdf file                 var data = ((DotNetOutputMemoryStream)o).Stream.GetBuffer();                 fs.Write(data, 0, data.Length);             }             Process.Start("HelloWorld.pdf");             System.Console.ReadLine();         }   Apache FOP be default using a Java’s Xalan to work with XML files. I didn’t find a way to replace this piece of code with equivalent from .NET standard library. If any error or warning will occure during generating the pdf file, on the console will ge shown, that’s why I inserted the last line in the sample above. The DotNetOutputMemoryStream this is my wrapper for the Java OutputStream. I have created it to have the possibility to exchange data between the .NET <-> Java objects. It’s implementation:   class DotNetOutputMemoryStream : OutputStream     {         private System.IO.MemoryStream ms = new System.IO.MemoryStream();         public System.IO.MemoryStream Stream         {             get             {                 return ms;             }         }         public override void write(int i)         {             ms.WriteByte((byte)i);         }         public override void write(byte[] b, int off, int len)         {             ms.Write(b, off, len);         }         public override void write(byte[] b)         {             ms.Write(b, 0, b.Length);         }         public override void close()         {             ms.Close();         }         public override void flush()         {             ms.Flush();         }     } The last thing we need, this is the HelloWorld.fo template.   <?xml version="1.0" encoding="utf-8"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">   <fo:layout-master-set>     <fo:simple-page-master master-name="simple"                   page-height="29.7cm"                   page-width="21cm"                   margin-top="1.8cm"                   margin-bottom="0.8cm"                   margin-left="1.6cm"                   margin-right="1.2cm">       <fo:region-body margin-top="3cm"/>       <fo:region-before extent="3cm"/>       <fo:region-after extent="1.5cm"/>     </fo:simple-page-master>   </fo:layout-master-set>   <fo:page-sequence master-reference="simple">     <fo:flow flow-name="xsl-region-body">       <fo:block font-size="18pt" color="black" text-align="center">         Hello, World!       </fo:block>     </fo:flow>   </fo:page-sequence> </fo:root>   I’m not going to explain how how this template is created, because this will be covered in the near future posts.   Generated pdf file should look that:

    Read the article

  • SQL SERVER – Weekly Series – Memory Lane – #038

    - by Pinal Dave
    Here is the list of selected articles of SQLAuthority.com across all these years. Instead of just listing all the articles I have selected a few of my most favorite articles and have listed them here with additional notes below it. Let me know which one of the following is your favorite article from memory lane. 2007 CASE Statement in ORDER BY Clause – ORDER BY using Variable This article is as per request from the Application Development Team Leader of my company. His team encountered code where the application was preparing string for ORDER BY clause of the SELECT statement. Application was passing this string as variable to Stored Procedure (SP) and SP was using EXEC to execute the SQL string. This is not good for performance as Stored Procedure has to recompile every time due to EXEC. sp_executesql can do the same task but still not the best performance. SSMS – View/Send Query Results to Text/Grid/Files Results to Text – CTRL + T Results to Grid – CTRL + D Results to File – CTRL + SHIFT + F 2008 Introduction to SPARSE Columns Part 2 I wrote about Introduction to SPARSE Columns Part 1. Let us understand the concept of the SPARSE column in more detail. I suggest you read the first part before continuing reading this article. All SPARSE columns are stored as one XML column in the database. Let us see some of the advantage and disadvantage of SPARSE column. Deferred Name Resolution How come when table name is incorrect SP can be created successfully but when an incorrect column is used SP cannot be created? 2009 Backup Timeline and Understanding of Database Restore Process in Full Recovery Model In general, databases backup in full recovery mode is taken in three different kinds of database files. Full Database Backup Differential Database Backup Log Backup Restore Sequence and Understanding NORECOVERY and RECOVERY While doing RESTORE Operation if you restoring database files, always use NORECOVER option as that will keep the database in a state where more backup file are restored. This will also keep database offline also to prevent any changes, which can create itegrity issues. Once all backup file is restored run RESTORE command with a RECOVERY option to get database online and operational. Four Different Ways to Find Recovery Model for Database Perhaps, the best thing about technical domain is that most of the things can be executed in more than one ways. It is always useful to know about the various methods of performing a single task. Two Methods to Retrieve List of Primary Keys and Foreign Keys of Database When Information Schema is used, we will not be able to discern between primary key and foreign key; we will have both the keys together. In the case of sys schema, we can query the data in our preferred way and can join this table to another table, which can retrieve additional data from the same. Get Last Running Query Based on SPID PID is returns sessions ID of the current user process. The acronym SPID comes from the name of its earlier version, Server Process ID. 2010 SELECT * FROM dual – Dual Equivalent Dual is a table that is created by Oracle together with data dictionary. It consists of exactly one column named “dummy”, and one record. The value of that record is X. You can check the content of the DUAL table using the following syntax. SELECT * FROM dual Identifying Statistics Used by Query Someone asked this question in my training class of query optimization and performance tuning.  “Can I know which statistics were used by my query?” 2011 SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 14 of 31 What are the basic functions for master, msdb, model, tempdb and resource databases? What is the Maximum Number of Index per Table? Explain Few of the New Features of SQL Server 2008 Management Studio Explain IntelliSense for Query Editing Explain MultiServer Query Explain Query Editor Regions Explain Object Explorer Enhancements Explain Activity Monitors SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 15 of 31 What is Service Broker? Where are SQL server Usernames and Passwords Stored in the SQL server? What is Policy Management? What is Database Mirroring? What are Sparse Columns? What does TOP Operator Do? What is CTE? What is MERGE Statement? What is Filtered Index? Which are the New Data Types Introduced in SQL SERVER 2008? SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 16 of 31 What are the Advantages of Using CTE? How can we Rewrite Sub-Queries into Simple Select Statements or with Joins? What is CLR? What are Synonyms? What is LINQ? What are Isolation Levels? What is Use of EXCEPT Clause? What is XPath? What is NOLOCK? What is the Difference between Update Lock and Exclusive Lock? SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 17 of 31 How will you Handle Error in SQL SERVER 2008? What is RAISEERROR? What is RAISEERROR? How to Rebuild the Master Database? What is the XML Datatype? What is Data Compression? What is Use of DBCC Commands? How to Copy the Tables, Schema and Views from one SQL Server to Another? How to Find Tables without Indexes? SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 18 of 31 How to Copy Data from One Table to Another Table? What is Catalog Views? What is PIVOT and UNPIVOT? What is a Filestream? What is SQLCMD? What do you mean by TABLESAMPLE? What is ROW_NUMBER()? What are Ranking Functions? What is Change Data Capture (CDC) in SQL Server 2008? SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 19 of 31 How can I Track the Changes or Identify the Latest Insert-Update-Delete from a Table? What is the CPU Pressure? How can I Get Data from a Database on Another Server? What is the Bookmark Lookup and RID Lookup? What is Difference between ROLLBACK IMMEDIATE and WITH NO_WAIT during ALTER DATABASE? What is Difference between GETDATE and SYSDATETIME in SQL Server 2008? How can I Check that whether Automatic Statistic Update is Enabled or not? How to Find Index Size for Each Index on Table? What is the Difference between Seek Predicate and Predicate? What are Basics of Policy Management? What are the Advantages of Policy Management? SQL SERVER – Interview Questions and Answers – Frequently Asked Questions – Day 20 of 31 What are Policy Management Terms? What is the ‘FILLFACTOR’? Where in MS SQL Server is ’100’ equal to ‘0’? What are Points to Remember while Using the FILLFACTOR Argument? What is a ROLLUP Clause? What are Various Limitations of the Views? What is a Covered index? When I Delete any Data from a Table, does the SQL Server reduce the size of that table? What are Wait Types? How to Stop Log File Growing too Big? If any Stored Procedure is Encrypted, then can we see its definition in Activity Monitor? 2012 Example of Width Sensitive and Width Insensitive Collation Width Sensitive Collation: A single-byte character (half-width) represented as single-byte and the same character represented as a double-byte character (full-width) are when compared are not equal the collation is width sensitive. In this example we have one table with two columns. One column has a collation of width sensitive and the second column has a collation of width insensitive. Find Column Used in Stored Procedure – Search Stored Procedure for Column Name Very interesting conversation about how to find column used in a stored procedure. There are two different characters in the story and both are having a conversation about how to find column in the stored procedure. Here are two part story Part 1 | Part 2 SQL SERVER – 2012 Functions – FORMAT() and CONCAT() – An Interesting Usage Generate Script for Schema and Data – SQL in Sixty Seconds #021 – Video In simple words, in many cases the database move from one place to another place. It is not always possible to back up and restore databases. There are possibilities when only part of the database (with schema and data) has to be moved. In this video we learn that we can easily generate script for schema for data and move from one server to another one. INFORMATION_SCHEMA.COLUMNS and Value Character Maximum Length -1 I often see the value -1 in the CHARACTER_MAXIMUM_LENGTH column of INFORMATION_SCHEMA.COLUMNS table. I understand that the length of any column can be between 0 to large number but I do not get it when I see value in negative (i.e. -1). Any insight on this subject? Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Memory Lane, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • JQGrdi PDF Export

    - by thanigai
    Originally posted on: http://geekswithblogs.net/thanigai/archive/2013/06/17/jqgrdi-pdf-export.aspxJQGrid PDF Export The aim of this article is to address the PDF export from client side grid frameworks. The solution is done using the ASP.Net MVC 4 and VisualStudio 2012. The article assumes the developer to have a fair amount of knowledge on ASP.Net MVC and C#. Tools Used Visual Studio 2012 ASP.Net MVC 4 Nuget Package Manager JQGrid  is one of the client grid framework built on top of the JQuery framework. It helps in building a beautiful grid with paging, sorting and exiting options. There are also other features available as extension plugins and developers can write their own if needed. You can download the JQgrid from the  JQGrid  homepage or as NUget package. I have given below the command to download the JQGrid through the package manager console. From the tools menu select “Library Package Manager” and then select “Package Manager Console”. I have given the screenshot below. This command will pull down the latest JQGrid package and adds them in the script folder. Once the script is downloaded and referenced in the project update the bundleconfig file to add the script reference in the pages. Bundleconfig can be found in the  App_Start  folder in the project structure. bundles .Add (newStyleBundle(“~/Content/jqgrid”).Include (“~/Content/ui.jqgrid.css”)); bundles.Add( newScriptBundle( “~/bundles/jquerygrid”) .Include( “~/Scripts/jqGrid/jquery.jqGrid*”)); Once added the config’s refer the bundles to the Views/Shared/LayoutPage.cshtml. Add the following lines to the head section of the page. @Styles.Render(“~/Content/jqgrid”) Add the following lines to the end of the page before html close tags. @Scripts.Render(“~/bundles/jquery”) @Scripts.Render(“~/bundles/jqueryui”) @Scripts.Render(“ ~/bundles/jquerygrid”)              That’s all to be done from the view perspective. Once these steps are done the developer can start coding for the JQGrid. In this example we will modify the HomeController for the demo. The index action will be the default action. We will add an argument for this index action. Let it be nullable bool. It’s just to mark the pdf request. In the Index.cshtml we will add a table tag with an id “ gridTable “. We will use this table for making the grid. Since JQGrid is an extension for the JQUery we will initialize the grid setting at the  script  section of the page. This script section is marked at the end of the page to improve performance. The script section is placed just below the bundle reference for JQuery and JQueryUI. This is the one of improvement factors from “ why slow” provided by yahoo. < tableid=“gridTable”class=“scroll”></ table> < inputtype=“button”value=“Export PDF”onclick=“exportPDF();“/>  @section scripts { <scripttype=“text/javascript”> $(document).ready(function(){$(“#gridTable”).jqGrid({datatype:“json”,url:‘@Url.Action(“GetCustomerDetails”)‘,mtype:‘GET’,colNames:["CustomerID","CustomerName","Location","PrimaryBusiness"],colModel:[{name:"CustomerID",width:40,index:"CustomerID",align:"center"},{name:"CustomerName",width:40,index:"CustomerName",align:"center"},{name:"Location",width:40,index:"Location",align:"center"},{name:"PrimaryBusiness",width:40,index:"PrimaryBusiness",align:"center"},],height:250,autowidth:true,sortorder:“asc”,rowNum:10,rowList:[5,10,15,20],sortname:“CustomerID”,viewrecords:true});});  function exportPDF (){ document . location = ‘ @ Url . Action ( “Index” ) ?pdf=true’ ; } </ script >  } The exportPDF methos just sets the document location to the Index action method with PDF Boolean as true just to mark for download PDF. An inmemory list collection is used for demo purpose. The  GetCustomerDetailsmethod is the server side action method that will provide the data as JSON list. We will see the method explanation below. [ HttpGet] publicJsonResultGetCustomerDetails(){ varresult=new { total=1, page=1, records=customerList.Count(), rows=( customerList.Select( e=>new { id=e.CustomerID, cell=newstring[]{ e.CustomerID.ToString(), e.CustomerName, e.Location, e.PrimaryBusiness}})) .ToArray()}; returnJson( result,  JsonRequestBehavior.AllowGet); }   JQGrid can understand the response data from server in certain format. The server method shown above is taking care of formatting the response so that JQGrid understand the data properly. The response data should contain totalpages, current page, full record count, rows of data with id and remaining columns as string array. The response is built using an anonymous object and will be sent as a MVC JsonResult. Since we are using HttpGet it’s better to mark the attribute as HttpGet and also the JSON requestbehavious as AllowGet. The inmemory list is initialized in the homecontroller constructor for reference. Public class HomeController : Controller{ private readonly Ilist < CustomerViewModel > customerList ; public HomeController (){ customerList=newList<CustomerViewModel>() { newCustomerViewModel{ CustomerID=100, CustomerName=“Sundar”, Location=“Chennai”, PrimaryBusiness=“Teacing”}, newCustomerViewModel{ CustomerID=101, CustomerName=“Sudhagar”, Location=“Chennai”, PrimaryBusiness=“Software”}, newCustomerViewModel{ CustomerID=102, CustomerName=“Thivagar”, Location=“China”, PrimaryBusiness=“SAP”}, }; }  publicActionResultIndex( bool?pdf){ if ( !pdf.HasValue){ returnView( customerList);} else{ stringfilePath=Server.MapPath( “Content”)  +“Sample.pdf”; ExportPDF( customerList,  new string[]{  “CustomerID”,  “CustomerName”,  “Location”,  “PrimaryBusiness” },  filePath); return File ( filePath ,  “application/pdf” , “list.pdf” ); }}   The index actionmethod has a Boolean argument named “pdf”. It’s used to indicate for PDF download. When the application starts this method is first hit for initial page request. For PDF operation a filename is generated and then sent to the  ExportPDF  method which will take care of generating the PDF from the datasource. The  ExportPDF method is listed below.  Private static void ExportPDF<TSource>(IList<TSource>customerList,string [] columns, string filePath){ FontheaderFont=FontFactory.GetFont( “Verdana”,  10,  Color.WHITE); Fontrowfont=FontFactory.GetFont( “Verdana”,  10,  Color.BLUE); Documentdocument=newDocument( PageSize.A4);  PdfWriter writer = PdfWriter . GetInstance ( document ,  new FileStream ( filePath ,  FileMode . OpenOrCreate )); document.Open(); PdfPTabletable=newPdfPTable( columns.Length); foreach ( varcolumnincolumns){ PdfPCellcell=newPdfPCell( newPhrase( column,  headerFont)); cell.BackgroundColor=Color.BLACK; table.AddCell( cell); }  foreach  ( var item in customerList ) { foreach ( varcolumnincolumns){ stringvalue=item.GetType() .GetProperty( column) .GetValue( item) .ToString(); PdfPCellcell5=newPdfPCell( newPhrase( value,  rowfont)); table.AddCell( cell5); } }  document.Add( table); document.Close(); }   iTextSharp is one of the pioneer in PDF export. It’s an opensource library readily available as NUget library. This command will pulldown latest available library. I am using the version 4.1.2.0. The latest version may have changed. There are three main things in this library. Document This is the document class which takes care of creating the document sheet with particular size. We have used A4 size. There is also an option to define the rectangle size. This document instance will be further used in next methods for reference. PdfWriter PdfWriter takes the filename and the document as the reference. This class enables the document class to generate the PDF content and save them in a file. Font Using the FONT class the developer can control the font features. Since I need a nice looking font I am giving the Verdana font. Following this PdfPTable and PdfPCell are used for generating the normal table layout. We have created two set of fonts for header and footer. Font headerFont=FontFactory .GetFont(“Verdana”, 10, Color .WHITE); Font rowfont=FontFactory .GetFont(“Verdana”, 10, Color .BLUE);   We are getting the header columns as string array. Columns argument array is looped and header is generated. We are using the headerfont for this purpose. PdfWriter writer=PdfWriter .GetInstance(document, newFileStream (filePath, FileMode.OpenOrCreate)); document.Open(); PdfPTabletable=newPdfPTable( columns.Length); foreach ( varcolumnincolumns){ PdfPCellcell=newPdfPCell( newPhrase( column,  headerFont)); cell.BackgroundColor=Color.BLACK; table.AddCell( cell); }   Then reflection is used to generate the row wise details and form the grid. foreach  (var item in customerList){ foreach ( varcolumnincolumns) { stringvalue=item.GetType() .GetProperty( column) .GetValue( item) .ToString(); PdfPCellcell5=newPdfPCell( newPhrase( value,  rowfont)); table.AddCell( cell5); } } document . Add ( table ); document . Close ();   Once the process id done the pdf table is added to the document and document is closed to write all the changes to the filepath given. Then the control moves to the controller which will take care of sending the response as a JSON result with a filename. If the file name is not given then the PDF will open in the same page otherwise a popup will open up asking whether to save the file or open file. Return File(filePath, “application/pdf”,“list.pdf”);   The final result screen is shown below. PDF file opened below to show the output. Conclusion: This is how the export pdf is done for JQGrid. The problem area that is addressed here is the clientside grid frameworks won’t support PDF’s export. In that time it’s better to have a fine grained control over the data and generated PDF. iTextSharp has helped us to achieve our goal.

    Read the article

  • CodePlex Daily Summary for Friday, August 08, 2014

    CodePlex Daily Summary for Friday, August 08, 2014Popular ReleasesSpace Engineers Server Manager: SESM V1.13: V1.13 - Added the restore option in the backup manager - Reenabled the map upload for the managersStrata v1.1 - Adobe Photoshop Like graphics editor: Strata 1.1: Version Strata 1.1: Available feutures: Drawing a layer; Adding a layer; Deleting a layer; Moving layers; Changing the order of layers; Hide / show layer; Saving as Project; Saving as Picture format (Jpg, Png, Gif) All interface in russian language. Saving - is Ok, But Opening have some display troublesEssence#: Nile (Alpha Build 20): The Nile release introduces ANSI-conformant streams into Essence#. It also fixes some significant bugs, and provides new utility scripts for use in developing Essence# code. The name Nile was chosen because it's the name of a rather big stream that's mentioned in the Bible--and we've been using a Biblical naming scheme for the Alpha releases. Recall that Moses as a babe was found among reeds along the banks of the Nile. So the Nile is a reed stream... FileStream Usage ExamplesTwo new exa...Instant Beautiful Browsing: IBB 14.3 Alpha: An alpha release of IBB. After 3 years of the last release this version is made from scratch, with tons of new features like: Make your own IBB aps. HTML 5. Better UI. Extreme Windows 8 resemblance. Photos. Store. Movement TONS of times smother compared to previous versions. Remember that this is AN ALPHA release, I hope I will have "IBB 14" finished by December. The documentation on how to create a new application for IBB will come next monthjQuery List DragSort: jQuery List DragSort 0.5.2: Fixed scrollContainer removing deprecated use of $.browser so should now work with latest version of jQuery. Added the ability to return false in dragEnd to revert sort order Project changes Added nuget package for dragsort https://www.nuget.org/packages/dragsort Converted repository from SVN to MercurialWix# (WixSharp) - managed interface for WiX: Release 1.0.0.0: Release 1.0.0.0 Custom UI Custom MSI Dialog Custom CLR Dialog External UIRecaptcha for .NET: Recaptcha for .NET v1.6.0: What's New?Bug fixes Optimized codeMath.NET Numerics: Math.NET Numerics v3.2.0: Linear Algebra: Vector.Map2 (map2 in F#), storage-optimized Linear Algebra: fix RemoveColumn/Row early index bound check (was not strict enough) Statistics: Entropy ~Jeff Mastry Interpolation: use Array.BinarySearch instead of local implementation ~Candy Chiu Resources: fix a corrupted exception message string Portable Build: support .Net 4.0 as well by using profile 328 instead of 344. .Net 3.5: F# extensions now support .Net 3.5 as well .Net 3.5: NuGet package now contains pro...AutomatedLab: AutomatedLab 2.2.0.0: 2.2.0 Support for Subordinate Certificate Authorities Installing software does no longer use workflows but background jobs, which is much faster Many performance improvements Removing a lab does no longer require to import it first if using the Path parameter Adjusted all sample scripts to work with version 2.x New validators to verify virtual switch settings Bug fixing 2.1.0 Support for external virtual switches CaRoot is a new role for installing Root Certificate Authorities ...babelua: 1.6.5.1: V1.6.5.1 - 2014.8.7New feature: Formatting code; Stability improvement: fix a bug that pop up error "System.Net.WebResponse EndGetResponse";Virto Commerce Enterprise Open Source eCommerce Platform (asp.net mvc): Virto Commerce 1.11: Virto Commerce Community Edition version 1.11. To install the SDK package, please refer to SDK getting started documentation To configure source code package, please refer to Source code getting started documentation This release includes many bug fixes and minor improvements. More details about this release can be found on our blog at http://blog.virtocommerce.com.Online Resume Parsing Using Aspose.Words for .NET: Resume_Parser: First Release of Resume Parser Application using Aspose.Words for .NET.Blade.Net: 3.0.0.0: Blade.Controls added: collection of MVVM and Prism friendly WPF controls and utilities InteractionRequest based implementation for OpenFile/SafeFile dialogs InteractionRequest based implementation for print dialog Drag&Drop behaviors Focus behaviors TextBox behaviors PopupWindowActionRegionAdapter PropagateInputBindingsToWindowBehavior Blade.Forest added: simple backlog tool Backlog items are structured via drag&drop in one tree Backlog items dragged to and structured in sepa...BBImageHandler - An image generator for DotNetNuke and ASP.NET: 01.06.00: Release notes V 1.6.0Added 2 configuration properties: ServerCacheExpiration (value in seconds,Default: 600 seconds) + ClientCacheExpiration (value in seconds, Default: 300 seconds) Fixed Client Caching (now sending 304 when cache time is not expired) Fixed bug when attaching watermark to indexed image formatRole Based View for Microsoft Dynamic CRM 2011 & 2013: Role based view for MS CRM 2011 Ver. 1.0: One of the very use full features called “Role Based View” in Microsoft Dynamics CRM 2011 & 2013 has been ignored by Microsoft. Now the functionality is provided with this small solution which will allowing you to have different views for an entity that can be assigned to different security roles. For example, Certain Views will not appear for the Sales person since their security level is lower than that of the Sales Manager. However Sales Manager can able to see those additional view.Json.NET: Json.NET 6.0 Release 4: New feature - Added Merge to LINQ to JSON New feature - Added JValue.CreateNull and JValue.CreateUndefined New feature - Added Windows Phone 8.1 support to .NET 4.0 portable assembly New feature - Added OverrideCreator to JsonObjectContract New feature - Added support for overriding the creation of interfaces and abstract types New feature - Added support for reading UUID BSON binary values as a Guid New feature - Added MetadataPropertyHandling.Ignore New feature - Improv...VidCoder: 1.5.24 Beta: Added NL-Means denoiser. Updated HandBrake core to SVN 6254. Added extra error handling to DVD player code to avoid a crash when the player was moved.PowerShell App Deployment Toolkit: PowerShell App Deployment Toolkit v3.1.5: *Added Send-Keys function to send a sequence of keys to an application window (Thanks to mmashwani) *Added 3 optimization/stability improvements to Execute-Process following MS best practice (Thanks to mmashwani) *Fixed issue where Execute-MSI did not use value from XML file for uninstall but instead ran all uninstalls silently by default *Fixed error on 1641 exit code (should be a success like 3010) *Fixed issue with error handling in Invoke-SCCMTask *Fixed issue with deferral dates where th...SEToolbox: SEToolbox 01.041.012 Release 1: Added voxel material textures to read in with mods. Fixed missing texture replacements for mods. Fixed rounding issue in raytrace code. Fixed repair issue with corrupt checkpoint file. Fixed issue with updated SE binaries 01.041.012 using new container configuration.Magick.NET: Magick.NET 6.8.9.601: Magick.NET linked with ImageMagick 6.8.9.6 Breaking changes: - Changed arguments for the Map method of MagickImage. - QuantizeSettings uses Riemersma by default.New ProjectsBaidu BCS: Baidu BCS (Baidu Cloud Storage) Server SDK. ????????SDK. .NET 4.0 or above. .NET 4.0?????Close Eye Assistant: a Close Eye Assistant using python3Dynamics AX IEIDE Project Explorer: This project is aiming to provide a set of useful features for Dynamics AX developers as well as administrators and is provided as an installable axmodel file.EFlogger - profiler for Entity Framework: Free and simple open source profiler for Entity Framework from 4-6 versionGuitar: i will continue to improve it.jQuery Table Pager Plugin: Simple jQuery plugin to paginate a table. JSJD: ????LFramework: LFrameworkMSDIS MVC Web: Sample ASP.NET MVC 4.0 using AngularJSPJS2: Not complete Powershell implementation in JavaScript.Seemile: SeemileShippety: Shippety is a web application for buying and printing postage labels. It's a client implementation for the EasyPost API written in HTML, Javascript and ASP.NET.Spending Monitor: With this application the user has the ability to create categories, retailers, and payment methods to track their spending in those categories. Strata v1.1 - Adobe Photoshop Like graphics editor: Strata - a graphical editor with layers mechanism similar to Adobe Photoshop. Layer - flat two-dimensional bitmap, where you can draw with the mouse.surfingkata: aTIKSN PowerShell Cmdlets: Bunch of cmdlets developed by TIKSN Lab???????: dfg???????: ????????????????: cvbvcbcv

    Read the article

  • JpegBitmapEncoder.Save() throws exception when writing image with metadata to MemoryStream

    - by Dmitry
    I am trying to set up metadata on JPG image what does not have it. You can't use in-place writer (InPlaceBitmapMetadataWriter) in this case, cuz there is no place for metadata in image. If I use FileStream as output - everything works fine. But if I try to use MemoryStream as output - JpegBitmapEncoder.Save() throws an exception (Exception from HRESULT: 0xC0000005). After some investigation I also found out what encoder can save image to memory stream if I supply null instead of metadata. I've made a very simplified and short example what reproduces the problem: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Media.Imaging; namespace JpegSaveTest { class Program { public static JpegBitmapEncoder SetUpMetadataOnStream(Stream src, string title) { uint padding = 2048; BitmapDecoder original; BitmapFrame framecopy, newframe; BitmapMetadata metadata; JpegBitmapEncoder output = new JpegBitmapEncoder(); src.Seek(0, SeekOrigin.Begin); original = JpegBitmapDecoder.Create(src, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); if (original.Frames[0] != null) { framecopy = (BitmapFrame)original.Frames[0].Clone(); if (original.Frames[0].Metadata != null) metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; else metadata = new BitmapMetadata("jpeg"); metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", padding); metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", padding); metadata.SetQuery("/xmp/PaddingSchema:Padding", padding); metadata.SetQuery("System.Title", title); newframe = BitmapFrame.Create(framecopy, framecopy.Thumbnail, metadata, original.Frames[0].ColorContexts); output.Frames.Add(newframe); } else { Exception ex = new Exception("Image contains no frames."); throw ex; } return output; } public static MemoryStream SetTagsInMemory(string sfname, string title) { Stream src, dst; JpegBitmapEncoder output; src = File.Open(sfname, FileMode.Open, FileAccess.Read, FileShare.Read); output = SetUpMetadataOnStream(src, title); dst = new MemoryStream(); output.Save(dst); src.Close(); return (MemoryStream)dst; } static void Main(string[] args) { string filename = "Z:\\dotnet\\gnom4.jpg"; MemoryStream s; s = SetTagsInMemory(filename, "test title"); } } } It is simple console application. To run it, replace filename variable content with path to any .jpg file without metadata (or use mine). Ofc I can just save image to temporary file first, close it, then open and copy to MemoryStream, but its too dirty and slow workaround. Any ideas about getting this working are welcome :)

    Read the article

  • Optimal storage of data structure for fast lookup and persistence

    - by Mikael Svenson
    Scenario I have the following methods: public void AddItemSecurity(int itemId, int[] userIds) public int[] GetValidItemIds(int userId) Initially I'm thinking storage on the form: itemId -> userId, userId, userId and userId -> itemId, itemId, itemId AddItemSecurity is based on how I get data from a third party API, GetValidItemIds is how I want to use it at runtime. There are potentially 2000 users and 10 million items. Item id's are on the form: 2007123456, 2010001234 (10 digits where first four represent the year). AddItemSecurity does not have to perform super fast, but GetValidIds needs to be subsecond. Also, if there is an update on an existing itemId I need to remove that itemId for users no longer in the list. I'm trying to think about how I should store this in an optimal fashion. Preferably on disk (with caching), but I want the code maintainable and clean. If the item id's had started at 0, I thought about creating a byte array the length of MaxItemId / 8 for each user, and set a true/false bit if the item was present or not. That would limit the array length to little over 1mb per user and give fast lookups as well as an easy way to update the list per user. By persisting this as Memory Mapped Files with the .Net 4 framework I think I would get decent caching as well (if the machine has enough RAM) without implementing caching logic myself. Parsing the id, stripping out the year, and store an array per year could be a solution. The ItemId - UserId[] list can be serialized directly to disk and read/write with a normal FileStream in order to persist the list and diff it when there are changes. Each time a new user is added all the lists have to updated as well, but this can be done nightly. Question Should I continue to try out this approach, or are there other paths which should be explored as well? I'm thinking SQL server will not perform fast enough, and it would give an overhead (at least if it's hosted on a different server), but my assumptions might be wrong. Any thought or insights on the matter is appreciated. And I want to try to solve it without adding too much hardware :) [Update 2010-03-31] I have now tested with SQL server 2008 under the following conditions. Table with two columns (userid,itemid) both are Int Clustered index on the two columns Added ~800.000 items for 180 users - Total of 144 million rows Allocated 4gb ram for SQL server Dual Core 2.66ghz laptop SSD disk Use a SqlDataReader to read all itemid's into a List Loop over all users If I run one thread it averages on 0.2 seconds. When I add a second thread it goes up to 0.4 seconds, which is still ok. From there on the results are decreasing. Adding a third thread brings alot of the queries up to 2 seonds. A forth thread, up to 4 seconds, a fifth spikes some of the queries up to 50 seconds. The CPU is roofing while this is going on, even on one thread. My test app takes some due to the speedy loop, and sql the rest. Which leads me to the conclusion that it won't scale very well. At least not on my tested hardware. Are there ways to optimize the database, say storing an array of int's per user instead of one record per item. But this makes it harder to remove items.

    Read the article

  • How do I record video to a local disk in AIR?

    - by Jim OHalloran
    I'm trying to record a webcam's video and audio to a FLV file stored on the users local hard disk. I have a version of this code working which uses NetConnection and NetStream to stream the video over a network to a FMS (Red5) server, but I'd like to be able to store the video locally for low bandwidth/flaky network situations. I'm using FLex 3.2 and AIR 1.5, so I don't believe there should be any sandbox restrictions which prevent this from occurring. Things I've seen: FileStream - Allows reading.writing local files but no .attachCamera and .attachAudio methids for creating a FLV. flvrecorder - Produces screen grabs from the web cam and creates it's own flv file. Doesn't support Audio. License prohibits commercial use. SimpleFLVWriter.as - Similar to flvrecorder without the wierd license. Doesn't support audio. This stackoverflow post - Which demonstrates the playback of a video from local disk using a NetConnection/NetStream. Given that I have a version already which uses NetStream to stream to the server I thought the last was most promising and went ahead and put together this demo application. The code compiles and runs without errors, but I don't have a FLV file on disk which the stop button is clicked. - <mx:Script> <![CDATA[ private var _diskStream:NetStream; private var _diskConn:NetConnection; private var _camera:Camera; private var _mic:Microphone; public function cmdStart_Click():void { _camera = Camera.getCamera(); _camera.setQuality(144000, 85); _camera.setMode(320, 240, 15); _camera.setKeyFrameInterval(60); _mic = Microphone.getMicrophone(); videoDisplay.attachCamera(_camera); _diskConn = new NetConnection(); _diskConn.connect(null); _diskStream = new NetStream(_diskConn); _diskStream.client = this; _diskStream.attachCamera(_camera); _diskStream.attachAudio(_mic); _diskStream.publish("file://c:/test.flv", "record"); } public function cmdStop_Click() { _diskStream.close(); videoDisplay.close(); } ]]> </mx:Script> <mx:VideoDisplay x="10" y="10" width="320" height="240" id="videoDisplay" /> <mx:Button x="10" y="258" label="Start" click="cmdStart_Click()" id="cmdStart"/> <mx:Button x="73" y="258" label="Stop" id="cmdStop" click="cmdStop_Click()"/> </mx:WindowedApplication> It seems to me that there's either something wrong with the above code which is preventing it from working, or NetStream just can't be abused in this wany to record video. What I'd like to know is, a) What (if anything) is wrong with the code above? b) If NetStream doesn't support recording to disk, are there any other alternatives which capture Audio AND Video to a file on the users local hard disk? Thanks in advance!

    Read the article

  • How to create Large resumable download from a secured location .NET

    - by Kelvin H
    I need to preface I'm not a .NET coder at all, but to get partial functionality, I modified a technet chunkedfilefetch.aspx script that uses chunked Data Reading and writing Streamed method of doing file transfer, to get me half-way. iStream = New System.IO.FileStream(path, System.IO.FileMode.Open, _ IO.FileAccess.Read, IO.FileShare.Read) dataToRead = iStream.Length Response.ContentType = "application/octet-stream" Response.AddHeader("Content-Length", file.Length.ToString()) Response.AddHeader("Content-Disposition", "attachment; filename=" & filedownload) ' Read and send the file 16,000 bytes at a time. ' While dataToRead 0 If Response.IsClientConnected Then length = iStream.Read(buffer, 0, 16000) Response.OutputStream.Write(buffer, 0, length) Response.Flush() ReDim buffer(16000) ' Clear the buffer ' dataToRead = dataToRead - length Else ' Prevent infinite loop if user disconnects ' dataToRead = -1 End If End While This works great on files up to 2GB and is fully functioning now.. But only one problem it doesn't allow for resume. I took the original code called it fetch.aspx and pass an orderNUM through the URL. fetch.aspx&ordernum=xxxxxxx It then reads the filename/location from the database occording to the ordernumber, and chunks it out from a secured location NOT under the webroot. I need a way to make this resumable, by the nature of the internet and large files people always get disconnected and would like to resume where they left off. But any resumable articles i've read, assume the file is within the webroot.. ie. http://www.devx.com/dotnet/Article/22533/1954 Great article and works well, but I need to stream from a secured location. I'm not a .NET coder at all, at best i can do a bit of coldfusion, if anyone could help me modify a handler to do this, i would really appreciate it. Requirements: I Have a working fetch.aspx script that functions well and uses the above code snippet as a base for the streamed downloading. Download files are large 600MB and are stored in a secured location outside of the webroot. Users click on the fetch.aspx to start the download, and would therefore be clicking it again if it was to fail. If the ext is a .ASPX and the file being sent is a AVI, clicking on it would completely bypass an IHTTP handler mapped to .AVI ext, so this confuses me From what I understand the browser will read and match etag value and file modified date to determine they are talking about the same file, then a subsequent accept-range is exchanged between the browser and IIS. Since this dialog happens with IIS, we need to use a handler to intercept and respond accordingly, but clicking on the link would send it to an ASPX file which the handeler needs to be on an AVI fiel.. Also confusing me. If there is a way to request the initial HTTP request header containing etag, accept-range into the normal .ASPX file, i could read those values and if the accept-range and etag exist, start chunking at that byte value somehow? but I couldn't find a way to transfer the http request headers since they seem to get lost at the IIS level. OrderNum which is passed in the URL string is unique and could be used as the ETag Response.AddHeader("ETag", request("ordernum")) Files need to be resumable and chunked out due to size. File extensions are .AVI so a handler could be written around it. IIS 6.0 Web Server Any help would really be appreciated, i've been reading and reading and downloading code, but none of the examples given meet my situation with the original file being streamed from outside of the webroot. Please help me get a handle on these httphandlers :)

    Read the article

  • Compress file to bytes for uploading to SQL Server

    - by Chris
    I am trying to zip files to an SQL Server database table. I can't ensure that the user of the tool has write priveledges on the source file folder so I want to load the file into memory, compress it to an array of bytes and insert it into my database. This below does not work. class ZipFileToSql { public event MessageHandler Message; protected virtual void OnMessage(string msg) { if (Message != null) { MessageHandlerEventArgs args = new MessageHandlerEventArgs(); args.Message = msg; Message(this, args); } } private int sourceFileId; private SqlConnection Conn; private string PathToFile; private bool isExecuting; public bool IsExecuting { get { return isExecuting; } } public int SourceFileId { get { return sourceFileId; } } public ZipFileToSql(string pathToFile, SqlConnection conn) { isExecuting = false; PathToFile = pathToFile; Conn = conn; } public void Execute() { isExecuting = true; byte[] data; byte[] cmpData; //create temp zip file OnMessage("Reading file to memory"); FileStream fs = File.OpenRead(PathToFile); data = new byte[fs.Length]; ReadWholeArray(fs, data); OnMessage("Zipping file to memory"); MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true); zip.Write(data, 0, data.Length); cmpData = new byte[ms.Length]; ReadWholeArray(ms, cmpData); OnMessage("Saving file to database"); using (SqlCommand cmd = Conn.CreateCommand()) { cmd.CommandText = @"MergeFileUploads"; cmd.CommandType = CommandType.StoredProcedure; //cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = data; cmd.Parameters.Add("@File", SqlDbType.VarBinary).Value = cmpData; SqlParameter p = new SqlParameter(); p.ParameterName = "@SourceFileId"; p.Direction = ParameterDirection.Output; p.SqlDbType = SqlDbType.Int; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); sourceFileId = (int)p.Value; } OnMessage("File Saved"); isExecuting = false; } private void ReadWholeArray(Stream stream, byte[] data) { int offset = 0; int remaining = data.Length; float Step = data.Length / 100; float NextStep = data.Length - Step; while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; if (remaining < NextStep) { NextStep -= Step; } } } }

    Read the article

  • Parsing google feed with linq to xml

    - by the_V
    Hi I'm trying to parse XML feed that I get via Google Contacts API with LINQ 2 XML. That's what feed looks like: <feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gContact="http://schemas.google.com/contact/2008" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gd="http://schemas.google.com/g/2005"> <id>[email protected]</id> <updated>2010-06-11T17:37:06.561Z</updated> <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact" /> <title type="text">My Contacts</title> <link rel="alternate" type="text/html" href="http://www.google.com/" /> <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full" /> <link rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full" /> <link rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full/batch" /> <link rel="self" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full?max-results=25" /> <author> <name>My NAme</name> <email>[email protected]</email> </author> <generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator> <openSearch:totalResults>19</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry> <id>http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/base/0</id> <updated>2010-01-26T20:34:03.802Z</updated> <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact" /> <title type="text">Contact name</title> <link rel="http://schemas.google.com/contacts/2008/rel#edit-photo" type="image/*" href="http://www.google.com/m8/feeds/photos/media/myemailaddress%40gmail.com/0/O-ydnzWMJcfZWqT-6gGetw" /> <link rel="http://schemas.google.com/contacts/2008/rel#photo" type="image/*" href="http://www.google.com/m8/feeds/photos/media/myemailaddress%40gmail.com/0" /> <link rel="self" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full/0" /> <link rel="edit" type="application/atom+xml" href="http://www.google.com/m8/feeds/contacts/myemailaddress%40gmail.com/full/0/1264538043802000" /> <gd:email rel="http://schemas.google.com/g/2005#other" address="[email protected]" primary="true" /> </entry> </feed> I've tried a number of things with linq 2 sql, but they didn't work. Even this simple code snipped doesn't work: using (FileStream stream = File.OpenRead("response.xml")) { XmlReader reader = XmlReader.Create(stream); XDocument doc = XDocument.Load(reader); XElement feed = doc.Element("feed"); if (feed == null) { Console.WriteLine("feed not found"); } XElement id = doc.Element("id"); if (id == null) { Console.WriteLine("id is null"); } } Problem is that both id and feed are null here. What wrong am I doing?

    Read the article

  • saved image in the picturebox shows no preview

    - by Nivas
    Hi iam new to C# and have loaded the image in the picture box using menustrip and have displayed some text using picturebox_Paint and label. now i tried to save the image (with image and text) using save event from the menustrip. in the saved location the file shows as no preview avaliable and when i tried to open the file it shows out of memory. can any one say where iam going worng.... my coades private void openToolStripMenuItem_Click(object sender, EventArgs e) { string file = ""; OpenFD.FileName = ""; OpenFD.Title = "open image"; OpenFD.InitialDirectory = "C"; OpenFD.Filter = "JPEG|.jpg|Bmp|.bmp|All Files|..*"; if (OpenFD.ShowDialog() == DialogResult.OK) { file = OpenFD.FileName; pictureBox1.Image = Image.FromFile(file); sz = pictureBox1.Size; a=sz.Width; b= sz.Height; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: { rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top); this.Invalidate(); y = flag.e; Application.DoEvents(); break; } } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { rect = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { using (Pen pen = new Pen(Color.Red, 2)) e.Graphics.DrawRectangle(pen, rect); //e.Graphics.DrawString(label1.Text, label1.Font, new // SolidBrush(label1.ForeColor), label1.Left - pictureBox1.Left, label1.Top - pictureBox1.Top); if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), label1.Bounds); } else if (label1.TextAlign == ContentAlignment.TopCenter) { SizeF size = e.Graphics.MeasureString(label1.Text, label1.Font); float left = ((float)this.Width + label1.Left) / 2 - size.Width / 2; RectangleF rect1 = new RectangleF(left, (float)label1.Top, size.Width, label1.Height); e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect1); } else { SizeF size = e.Graphics.MeasureString(label1.Text, label1.Font); float left = (float)label1.Width - size.Width + label1.Left; RectangleF rect1 = new RectangleF(left, (float)label1.Top, size.Width, label1.Height); e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect1); } label1.Top = rect.Top; label1.Left = rect.Left; label1.Width = rect.Width; label1.Height = rect.Height; } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog SaveFD1 = new SaveFileDialog(); //string Sd_file = ""; SaveFD1.FileName = ""; SaveFD1.InitialDirectory = "C"; SaveFD1.Title = "save file Name"; SaveFD1.Filter= "JPG|.jpg|Bmp|.bmp"; if (SaveFD1.ShowDialog() != DialogResult.Cancel) { System.IO.Stream filename = (System.IO.FileStream)SaveFD1.OpenFile(); if (SaveFD1.Filter == "JPG") pictureBox1.Image.Save(SaveFD1.FileName); //pictureBox1.Image.Save (filename, System.Drawing.Imaging.ImageFormat.Jpeg); else if (SaveFD1.Filter == "Bmp") { //pictureBox1.Image.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp); } filename.Close(); } }

    Read the article

  • SQL Server 08 Express error when connecting to localhost - "Timeout expired". Works with ::1 or 127

    - by Adam A
    EDIT New info: Navigating to localhost:1434 in Chrome gives me an "ERR_EMPTY_RESPONSE", while other ports give me an "Oops! This link appears to be broken". So it seems to binding ok there? So here's my setup so far: I've configured Windows Firewall to allow TCP on 1433 and UDP on 1434. I've set up SQL Server to use any IP on Port 1433 (using the SQL Server Configuration Manager). My hosts file contains the default entries ("127.0.0.1 localhost" and "::1 localhost"). I sometimes have a debug session of Visual Web Developer running a webserver, but it's on a specific port (localhost:5XXXX). What I've tried: I CAN ping localhost in a cmd prompt. I CAN connect to the database through SSMS if I specify 127.0.0.1 or ::1 as the server name. I CAN'T connect to the database through SSMS (or ADO.NET) if I specify localhost as the server name. I've tried both Windows and SQL Authentication The error I get is the standard Can't connect to localhost. Additional Information -- Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. (Microsoft Sql Server) Other considerations: Stopping the Visual Web Developer web server from the taskbar doesn't affect the sql problem. The SQL error log says that it's listening on some piped name url at start up (I don't see how this would affect localhost but not 127.0.0.1 though). I could probably just use 127.0.0.1 everywhere, but it scares me that localhost isn't working and I'd like to figure out why. I'm not much of a networking or sql server guy so I'm stuck. If you want me to try anything to help diagnose just put it in a comment and I'll give it a go. Netstat results: Setting SDK environment relative to C:\Program Files\Microsoft SDKs\Windows\v6.1 Targeting Windows Server 2008 x86 DEBUG C:\Program Files\Microsoft SDKs\Windows\v6.1netstat -ano | findstr 1434 UDP 0.0.0.0:1434 *:* 6868 UDP [::]:1434 *:* 6868 C:\Program Files\Microsoft SDKs\Windows\v6.1netstat -ano | findstr 1433 TCP 0.0.0.0:1433 0.0.0.0:0 LISTENING 2268 TCP 127.0.0.1:1433 127.0.0.1:50758 ESTABLISHED 2268 TCP 127.0.0.1:50758 127.0.0.1:1433 ESTABLISHED 5008 TCP [::]:1433 [::]:0 LISTENING 2268 TCP [::1]:1433 [::1]:51202 ESTABLISHED 2268 TCP [::1]:1433 [::1]:51616 ESTABLISHED 2268 TCP [::1]:51202 [::1]:1433 ESTABLISHED 5008 TCP [::1]:51616 [::1]:1433 ESTABLISHED 5008 C:\Program Files\Microsoft SDKs\Windows\v6.1 SQL Server Log File: In case it helps 2010-01-30 12:58:59.01 Server Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86) Mar 29 2009 10:27:29 Copyright (c) 1988-2008 Microsoft Corporation Express Edition on Windows NT 6.0 (Build 6002: Service Pack 2) 2010-01-30 12:58:59.01 Server (c) 2005 Microsoft Corporation. 2010-01-30 12:58:59.01 Server All rights reserved. 2010-01-30 12:58:59.01 Server Server process ID is 2268. 2010-01-30 12:58:59.01 Server System Manufacturer: 'Dell Inc.', System Model: 'Inspiron 1545'. 2010-01-30 12:58:59.01 Server Authentication mode is MIXED. 2010-01-30 12:58:59.02 Server Logging SQL Server messages in file 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\ERRORLOG'. 2010-01-30 12:58:59.02 Server This instance of SQL Server last reported using a process ID of 7396 at 1/30/2010 12:57:38 PM (local) 1/30/2010 5:57:38 PM (UTC). This is an informational message only; no user action is required. 2010-01-30 12:58:59.02 Server Registry startup parameters: -d c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\master.mdf -e c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\ERRORLOG -l c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\mastlog.ldf 2010-01-30 12:58:59.02 Server SQL Server is starting at normal priority base (=7). This is an informational message only. No user action is required. 2010-01-30 12:58:59.02 Server Detected 2 CPUs. This is an informational message; no user action is required. 2010-01-30 12:58:59.08 Server Using dynamic lock allocation. Initial allocation of 2500 Lock blocks and 5000 Lock Owner blocks per node. This is an informational message only. No user action is required. 2010-01-30 12:58:59.17 Server Node configuration: node 0: CPU mask: 0x00000003 Active CPU mask: 0x00000003. This message provides a description of the NUMA configuration for this computer. This is an informational message only. No user action is required. 2010-01-30 12:58:59.30 spid7s Starting up database 'master'. 2010-01-30 12:58:59.41 spid7s Recovery is writing a checkpoint in database 'master' (1). This is an informational message only. No user action is required. 2010-01-30 12:58:59.67 spid7s FILESTREAM: effective level = 0, configured level = 0, file system access share name = 'SQLEXPRESS'. 2010-01-30 12:58:59.92 spid7s SQL Trace ID 1 was started by login "sa". 2010-01-30 12:58:59.94 spid7s Starting up database 'mssqlsystemresource'. 2010-01-30 12:58:59.95 spid7s The resource database build version is 10.00.2531. This is an informational message only. No user action is required. 2010-01-30 12:59:00.82 spid7s Server name is 'DELL\SQLEXPRESS'. This is an informational message only. No user action is required. 2010-01-30 12:59:00.83 Server A self-generated certificate was successfully loaded for encryption. 2010-01-30 12:59:00.84 Server Server is listening on [ 'any' 1433]. 2010-01-30 12:59:00.84 Server Server is listening on [ 'any' 1433]. 2010-01-30 12:59:00.84 spid10s Starting up database 'model'. 2010-01-30 12:59:00.85 Server Server local connection provider is ready to accept connection on [ \\.\pipe\SQLLocal\SQLEXPRESS ]. 2010-01-30 12:59:00.86 Server Server local connection provider is ready to accept connection on [ \\.\pipe\MSSQL$SQLEXPRESS\sql\query ]. 2010-01-30 12:59:00.86 Server Dedicated administrator connection support was not started because it is disabled on this edition of SQL Server. If you want to use a dedicated administrator connection, restart SQL Server using the trace flag 7806. This is an informational message only. No user action is required. 2010-01-30 12:59:00.87 Server The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service. Error: 0x54b, state: 3. Failure to register an SPN may cause integrated authentication to fall back to NTLM instead of Kerberos. This is an informational message. Further action is only required if Kerberos authentication is required by authentication policies. 2010-01-30 12:59:00.87 spid7s Informational: No full-text supported languages found. 2010-01-30 12:59:00.87 Server SQL Server is now ready for client connections. This is an informational message; no user action is required. 2010-01-30 12:59:00.91 spid7s Starting up database 'msdb'. 2010-01-30 12:59:01.21 spid10s Clearing tempdb database. 2010-01-30 12:59:02.78 spid10s Starting up database 'tempdb'. 2010-01-30 12:59:03.30 spid13s The Service Broker protocol transport is disabled or not configured. 2010-01-30 12:59:03.30 spid13s The Database Mirroring protocol transport is disabled or not configured. 2010-01-30 12:59:03.31 spid7s Recovery is complete. This is an informational message only. No user action is required. 2010-01-30 12:59:03.31 spid13s Service Broker manager has started.

    Read the article

  • SQL Server 08 Express error when connecting to localhost - "Timeout expired". Works with ::1 or 127.0.0.1

    - by Adam A
    EDIT New info: Navigating to localhost:1434 in Chrome gives me an "ERR_EMPTY_RESPONSE", while other ports give me an "Oops! This link appears to be broken". So it seems to binding ok there? So here's my setup so far: I've configured Windows Firewall to allow TCP on 1433 and UDP on 1434. I've set up SQL Server to use any IP on Port 1433 (using the SQL Server Configuration Manager). My hosts file contains the default entries ("127.0.0.1 localhost" and "::1 localhost"). I sometimes have a debug session of Visual Web Developer running a webserver, but it's on a specific port (localhost:5XXXX). What I've tried: I CAN ping localhost in a cmd prompt. I CAN connect to the database through SSMS if I specify 127.0.0.1 or ::1 as the server name. I CAN'T connect to the database through SSMS (or ADO.NET) if I specify localhost as the server name. I've tried both Windows and SQL Authentication The error I get is the standard Can't connect to localhost. Additional Information -- Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. (Microsoft Sql Server) Other considerations: Stopping the Visual Web Developer web server from the taskbar doesn't affect the sql problem. The SQL error log says that it's listening on some piped name url at start up (I don't see how this would affect localhost but not 127.0.0.1 though). I could probably just use 127.0.0.1 everywhere, but it scares me that localhost isn't working and I'd like to figure out why. I'm not much of a networking or sql server guy so I'm stuck. If you want me to try anything to help diagnose just put it in a comment and I'll give it a go. Netstat results: Setting SDK environment relative to C:\Program Files\Microsoft SDKs\Windows\v6.1 Targeting Windows Server 2008 x86 DEBUG C:\Program Files\Microsoft SDKs\Windows\v6.1netstat -ano | findstr 1434 UDP 0.0.0.0:1434 *:* 6868 UDP [::]:1434 *:* 6868 C:\Program Files\Microsoft SDKs\Windows\v6.1netstat -ano | findstr 1433 TCP 0.0.0.0:1433 0.0.0.0:0 LISTENING 2268 TCP 127.0.0.1:1433 127.0.0.1:50758 ESTABLISHED 2268 TCP 127.0.0.1:50758 127.0.0.1:1433 ESTABLISHED 5008 TCP [::]:1433 [::]:0 LISTENING 2268 TCP [::1]:1433 [::1]:51202 ESTABLISHED 2268 TCP [::1]:1433 [::1]:51616 ESTABLISHED 2268 TCP [::1]:51202 [::1]:1433 ESTABLISHED 5008 TCP [::1]:51616 [::1]:1433 ESTABLISHED 5008 C:\Program Files\Microsoft SDKs\Windows\v6.1 SQL Server Log File: In case it helps 2010-01-30 12:58:59.01 Server Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86) Mar 29 2009 10:27:29 Copyright (c) 1988-2008 Microsoft Corporation Express Edition on Windows NT 6.0 (Build 6002: Service Pack 2) 2010-01-30 12:58:59.01 Server (c) 2005 Microsoft Corporation. 2010-01-30 12:58:59.01 Server All rights reserved. 2010-01-30 12:58:59.01 Server Server process ID is 2268. 2010-01-30 12:58:59.01 Server System Manufacturer: 'Dell Inc.', System Model: 'Inspiron 1545'. 2010-01-30 12:58:59.01 Server Authentication mode is MIXED. 2010-01-30 12:58:59.02 Server Logging SQL Server messages in file 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\ERRORLOG'. 2010-01-30 12:58:59.02 Server This instance of SQL Server last reported using a process ID of 7396 at 1/30/2010 12:57:38 PM (local) 1/30/2010 5:57:38 PM (UTC). This is an informational message only; no user action is required. 2010-01-30 12:58:59.02 Server Registry startup parameters: -d c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\master.mdf -e c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\ERRORLOG -l c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\mastlog.ldf 2010-01-30 12:58:59.02 Server SQL Server is starting at normal priority base (=7). This is an informational message only. No user action is required. 2010-01-30 12:58:59.02 Server Detected 2 CPUs. This is an informational message; no user action is required. 2010-01-30 12:58:59.08 Server Using dynamic lock allocation. Initial allocation of 2500 Lock blocks and 5000 Lock Owner blocks per node. This is an informational message only. No user action is required. 2010-01-30 12:58:59.17 Server Node configuration: node 0: CPU mask: 0x00000003 Active CPU mask: 0x00000003. This message provides a description of the NUMA configuration for this computer. This is an informational message only. No user action is required. 2010-01-30 12:58:59.30 spid7s Starting up database 'master'. 2010-01-30 12:58:59.41 spid7s Recovery is writing a checkpoint in database 'master' (1). This is an informational message only. No user action is required. 2010-01-30 12:58:59.67 spid7s FILESTREAM: effective level = 0, configured level = 0, file system access share name = 'SQLEXPRESS'. 2010-01-30 12:58:59.92 spid7s SQL Trace ID 1 was started by login "sa". 2010-01-30 12:58:59.94 spid7s Starting up database 'mssqlsystemresource'. 2010-01-30 12:58:59.95 spid7s The resource database build version is 10.00.2531. This is an informational message only. No user action is required. 2010-01-30 12:59:00.82 spid7s Server name is 'DELL\SQLEXPRESS'. This is an informational message only. No user action is required. 2010-01-30 12:59:00.83 Server A self-generated certificate was successfully loaded for encryption. 2010-01-30 12:59:00.84 Server Server is listening on [ 'any' 1433]. 2010-01-30 12:59:00.84 Server Server is listening on [ 'any' 1433]. 2010-01-30 12:59:00.84 spid10s Starting up database 'model'. 2010-01-30 12:59:00.85 Server Server local connection provider is ready to accept connection on [ \\.\pipe\SQLLocal\SQLEXPRESS ]. 2010-01-30 12:59:00.86 Server Server local connection provider is ready to accept connection on [ \\.\pipe\MSSQL$SQLEXPRESS\sql\query ]. 2010-01-30 12:59:00.86 Server Dedicated administrator connection support was not started because it is disabled on this edition of SQL Server. If you want to use a dedicated administrator connection, restart SQL Server using the trace flag 7806. This is an informational message only. No user action is required. 2010-01-30 12:59:00.87 Server The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service. Error: 0x54b, state: 3. Failure to register an SPN may cause integrated authentication to fall back to NTLM instead of Kerberos. This is an informational message. Further action is only required if Kerberos authentication is required by authentication policies. 2010-01-30 12:59:00.87 spid7s Informational: No full-text supported languages found. 2010-01-30 12:59:00.87 Server SQL Server is now ready for client connections. This is an informational message; no user action is required. 2010-01-30 12:59:00.91 spid7s Starting up database 'msdb'. 2010-01-30 12:59:01.21 spid10s Clearing tempdb database. 2010-01-30 12:59:02.78 spid10s Starting up database 'tempdb'. 2010-01-30 12:59:03.30 spid13s The Service Broker protocol transport is disabled or not configured. 2010-01-30 12:59:03.30 spid13s The Database Mirroring protocol transport is disabled or not configured. 2010-01-30 12:59:03.31 spid7s Recovery is complete. This is an informational message only. No user action is required. 2010-01-30 12:59:03.31 spid13s Service Broker manager has started.

    Read the article

  • SQL Server Express 2008 R2 Installation error at Windows 7

    - by Shai Sherman
    Hello, I created install script that will install SQL Server 2008 R2 on windows XP SP3, windows vista and windows 7. One of the command that i used in the installation is for silent installation of SQL Server 2008 R2. When i install it on windows XP everything works just fine but when i try to install it on Windows 7 i get an error. What am I doing wrong? Here is the command line that i use: "Setup.exe /ConfigurationFile=Mysetup.ini" Mysetup.ini file: -------------------------------------Start of ini file --------------------------------- ;SQL SERVER 2008 R2 Configuration File ;Version 1.0, 5 May 2010 ; [SQLSERVER2008] ; Specify the Instance ID for the SQL Server features you have specified. SQL Server directory structure, registry structure, and service names will reflect the instance ID of the SQL Server instance. INSTANCEID="MSSQLSERVER" ; Specifies a Setup work flow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter. ACTION="Install" ; Specifies features to install, uninstall, or upgrade. The list of top-level features include SQL, AS, RS, IS, and Tools. The SQL feature will install the database engine, replication, and full-text. The Tools feature will install Management Tools, Books online, Business Intelligence Development Studio, and other shared components. FEATURES=SQLENGINE ; Displays the command line parameters usage HELP="False" ; Specifies that the detailed Setup log should be piped to the console. INDICATEPROGRESS="False" ; Setup will not display any user interface. QUIET="False" ; Setup will display progress only without any user interaction. QUIETSIMPLE="True" ; Specifies that Setup should install into WOW64. This command line argument is not supported on an IA64 or a 32-bit system. ;X86="False" ; Specifies the path to the installation media folder where setup.exe is located. ;MEDIASOURCE="z:\" ; Detailed help for command line argument ENU has not been defined yet. ENU="True" ; Parameter that controls the user interface behavior. Valid values are Normal for the full UI, and AutoAdvance for a simplied UI. ; UIMODE="Normal" ; Specify if errors can be reported to Microsoft to improve future SQL Server releases. Specify 1 or True to enable and 0 or False to disable this feature. ERRORREPORTING="False" ; Specify the root installation directory for native shared components. ;INSTALLSHAREDDIR="D:\Program Files\Microsoft SQL Server" ; Specify the root installation directory for the WOW64 shared components. ;INSTALLSHAREDWOWDIR="D:\Program Files (x86)\Microsoft SQL Server" ; Specify the installation directory. ;INSTANCEDIR="D:\Program Files\Microsoft SQL Server" ; Specify that SQL Server feature usage data can be collected and sent to Microsoft. Specify 1 or True to enable and 0 or False to disable this feature. SQMREPORTING="False" ; Specify a default or named instance. MSSQLSERVER is the default instance for non-Express editions and SQLExpress for Express editions. This parameter is required when installing the SQL Server Database Engine (SQL), Analysis Services (AS), or Reporting Services (RS). INSTANCENAME="SQLEXPRESS" SECURITYMODE=SQL SAPWD=SystemAdmin ; Agent account name AGTSVCACCOUNT="NT AUTHORITY\NETWORK SERVICE" ; Auto-start service after installation. AGTSVCSTARTUPTYPE="Manual" ; Startup type for Integration Services. ;ISSVCSTARTUPTYPE="Automatic" ; Account for Integration Services: Domain\User or system account. ;ISSVCACCOUNT="NT AUTHORITY\NetworkService" ; Controls the service startup type setting after the service has been created. ;ASSVCSTARTUPTYPE="Automatic" ; The collation to be used by Analysis Services. ;ASCOLLATION="Latin1_General_CI_AS" ; The location for the Analysis Services data files. ;ASDATADIR="Data" ; The location for the Analysis Services log files. ;ASLOGDIR="Log" ; The location for the Analysis Services backup files. ;ASBACKUPDIR="Backup" ; The location for the Analysis Services temporary files. ;ASTEMPDIR="Temp" ; The location for the Analysis Services configuration files. ;ASCONFIGDIR="Config" ; Specifies whether or not the MSOLAP provider is allowed to run in process. ;ASPROVIDERMSOLAP="1" ; A port number used to connect to the SharePoint Central Administration web application. ;FARMADMINPORT="0" ; Startup type for the SQL Server service. SQLSVCSTARTUPTYPE="Automatic" ; Level to enable FILESTREAM feature at (0, 1, 2 or 3). FILESTREAMLEVEL="0" ; Set to "1" to enable RANU for SQL Server Express. ENABLERANU="1" ; Specifies a Windows collation or an SQL collation to use for the Database Engine. SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS" ; Account for SQL Server service: Domain\User or system account. SQLSVCACCOUNT="NT Authority\System" ; Default directory for the Database Engine user databases. ;SQLUSERDBDIR="K:\Microsoft SQL Server\MSSQL\Data" ; Default directory for the Database Engine user database logs. ;SQLUSERDBLOGDIR="L:\Microsoft SQL Server\MSSQL\Data\Logs" ; Directory for Database Engine TempDB files. ;SQLTEMPDBDIR="T:\Microsoft SQL Server\MSSQL\Data" ; Directory for the Database Engine TempDB log files. ;SQLTEMPDBLOGDIR="T:\Microsoft SQL Server\MSSQL\Data\Logs" ; Provision current user as a Database Engine system administrator for SQL Server 2008 R2 Express. ADDCURRENTUSERASSQLADMIN="True" ; Specify 0 to disable or 1 to enable the TCP/IP protocol. TCPENABLED="1" ; Specify 0 to disable or 1 to enable the Named Pipes protocol. NPENABLED="0" ; Startup type for Browser Service. BROWSERSVCSTARTUPTYPE="Automatic" ; Specifies how the startup mode of the report server NT service. When ; Manual - Service startup is manual mode (default). ; Automatic - Service startup is automatic mode. ; Disabled - Service is disabled ;RSSVCSTARTUPTYPE="Automatic" ; Specifies which mode report server is installed in. ; Default value: “FilesOnly” ;RSINSTALLMODE="FilesOnlyMode" ; Accept SQL Server 2008 R2 license terms IACCEPTSQLSERVERLICENSETERMS="TRUE" ;setup.exe /CONFIGURATIONFILE=Mysetup.ini /INDICATEPROGRESS --------------------------- End of ini file ------------------------------------- And i get this error: 2010-08-31 18:05:53 Slp: Error result: -2068119551 2010-08-31 18:05:53 Slp: Result facility code: 1211 2010-08-31 18:05:53 Slp: Result error code: 1 2010-08-31 18:05:53 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine 2010-08-31 18:05:53 Slp: Sco: Attempting to open registry subkey 2010-08-31 18:05:53 Slp: Sco: Attempting to open registry subkey Software\Microsoft\PCHealth\ErrorReporting\DW\Installed 2010-08-31 18:05:53 Slp: Sco: Attempting to get registry value DW0200 2010-08-31 18:05:53 Slp: Submitted 1 of 1 failures to the Watson data repository What the meaning of this? What do i need to do to fix that problem? Here is the Summary file: Overall summary: Final result: SQL Server installation failed. To continue, investigate the reason for the failure, correct the problem, uninstall SQL Server, and then rerun SQL Server Setup. Exit code (Decimal): -2068119551 Exit facility code: 1211 Exit error code: 1 Exit message: SQL Server installation failed. To continue, investigate the reason for the failure, correct the problem, uninstall SQL Server, and then rerun SQL Server Setup. Start time: 2010-08-31 18:03:44 End time: 2010-08-31 18:05:51 Requested action: Install Log with failure: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20100831_180236\Detail.txt Exception help link: http%3a%2f%2fgo.microsoft.com%2ffwlink%3fLinkId%3d20476%26ProdName%3dMicrosoft%2bSQL%2bServer%26EvtSrc%3dsetup.rll%26EvtID%3d50000%26ProdVer%3d10.50.1600.1%26EvtType%3d0x6121810A%400xC24842DB Machine Properties: Machine name: NVR Machine processor count: 2 OS version: Windows 7 OS service pack: OS region: United States OS language: English (United States) OS architecture: x86 Process architecture: 32 Bit OS clustered: No Product features discovered: Product Instance Instance ID Feature Language Edition Version Clustered Package properties: Description: SQL Server Database Services 2008 R2 ProductName: SQL Server 2008 R2 Type: RTM Version: 10 SPLevel: 0 Installation location: C:\Disk1\setupsql\x86\setup\ Installation edition: EXPRESS User Input Settings: ACTION: Install ADDCURRENTUSERASSQLADMIN: True AGTSVCACCOUNT: NT AUTHORITY\NETWORK SERVICE AGTSVCPASSWORD: * AGTSVCSTARTUPTYPE: Disabled ASBACKUPDIR: Backup ASCOLLATION: Latin1_General_CI_AS ASCONFIGDIR: Config ASDATADIR: Data ASDOMAINGROUP: ASLOGDIR: Log ASPROVIDERMSOLAP: 1 ASSVCACCOUNT: ASSVCPASSWORD: * ASSVCSTARTUPTYPE: Automatic ASSYSADMINACCOUNTS: ASTEMPDIR: Temp BROWSERSVCSTARTUPTYPE: Automatic CONFIGURATIONFILE: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20100831_180236\ConfigurationFile.ini CUSOURCE: ENABLERANU: True ENU: True ERRORREPORTING: False FARMACCOUNT: FARMADMINPORT: 0 FARMPASSWORD: * FEATURES: SQLENGINE FILESTREAMLEVEL: 0 FILESTREAMSHARENAME: FTSVCACCOUNT: FTSVCPASSWORD: * HELP: False IACCEPTSQLSERVERLICENSETERMS: True INDICATEPROGRESS: False INSTALLSHAREDDIR: C:\Program Files\Microsoft SQL Server\ INSTALLSHAREDWOWDIR: C:\Program Files\Microsoft SQL Server\ INSTALLSQLDATADIR: INSTANCEDIR: C:\Program Files\Microsoft SQL Server\ INSTANCEID: MSSQLSERVER INSTANCENAME: SQLEXPRESS ISSVCACCOUNT: NT AUTHORITY\NetworkService ISSVCPASSWORD: * ISSVCSTARTUPTYPE: Automatic NPENABLED: 0 PASSPHRASE: * PCUSOURCE: PID: * QUIET: False QUIETSIMPLE: True ROLE: AllFeatures_WithDefaults RSINSTALLMODE: FilesOnlyMode RSSVCACCOUNT: NT AUTHORITY\NETWORK SERVICE RSSVCPASSWORD: * RSSVCSTARTUPTYPE: Automatic SAPWD: * SECURITYMODE: SQL SQLBACKUPDIR: SQLCOLLATION: SQL_Latin1_General_CP1_CI_AS SQLSVCACCOUNT: NT Authority\System SQLSVCPASSWORD: * SQLSVCSTARTUPTYPE: Automatic SQLSYSADMINACCOUNTS: SQLTEMPDBDIR: SQLTEMPDBLOGDIR: SQLUSERDBDIR: SQLUSERDBLOGDIR: SQMREPORTING: False TCPENABLED: 1 UIMODE: AutoAdvance X86: False Configuration file: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20100831_180236\ConfigurationFile.ini Detailed results: Feature: Database Engine Services Status: Failed: see logs for details MSI status: Passed Configuration status: Failed: see details below Configuration error code: 0x0A2FBD17@1211@1 Configuration error description: The process cannot access the file because it is being used by another process. Configuration log: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20100831_180236\Detail.txt Rules with failures: Global rules: Scenario specific rules: Rules report file: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20100831_180236\SystemConfigurationCheck_Report.htm What should I do and why does this problem occur? Thanks , Shai.

    Read the article

  • C# creating a queue to handle jobs triggered by FileSystemWatcher

    - by John S
    I have built a small tray app that will watch a folder and when a new file is added it runs a job. The job is to watch for video files and convert them to .mp4 using handBrakeCli. I have all this logic worked out. The problem I run into is that if there is more than one file I want it to queue the job til the prior one is complete. I am fairly new to c# and I am not sure of the best way to handle this. one idea is to create a queue somehow, a file to store the commands in order maybe, then execute the next one after the process is complete. We are dealing with large movie files here so it can take a while. I am doing this on a quad core with 8gb of RAM and it seems to generally take about 30mins to complete a full length movie. here is the code I have so far. there are some bits in here that are for future functionality so it refers to some classes that you wont see but it doesnt matter as they arent used here. any suggestions are welcome. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Threading; namespace movie_converter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string hbCli; string cmd; string file; string strfilter = "*.*"; string[] filter = new string[3] { ".mkv", ".avi", ".wmv" }; //static list of types List<string> Ext = new List<string>(); //list of extensions to watch (dynamic) NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon(); private void SetUpTrayIcon() { notifyIcon.BalloonTipText = "Movie Converter is running minimized."; notifyIcon.BalloonTipTitle = "I'm still here"; notifyIcon.Text = "John's movie converter"; notifyIcon.Icon = new Icon(@"C:\\Users\\John\\Pictures\\appicon.ico"); notifyIcon.Click += new EventHandler(notifyIcon_Click); if (notifyIcon != null) { notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(2000); } } private void Form_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) { this.Hide(); SetUpTrayIcon(); } } private void notifyIcon_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; notifyIcon.Visible = false; } public void Watcher() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = textBox1.Text + "\\"; //path to watch watcher.Filter = strfilter; //what types to look for set to * and i will filter later as it cant accept an array watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName; //properties to look at watcher.IncludeSubdirectories = true; //scan subdirs watcher.Created += new FileSystemEventHandler(OnChanged); //TODO: make this only run if the files are of a certain type watcher.EnableRaisingEvents = true; // start the watcher } static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; } // Define the event handlers. private void OnChanged(object source, FileSystemEventArgs e) { string sFile = e.FullPath; //check that file is available FileInfo fileInfo = new FileInfo(sFile); while (IsFileLocked(fileInfo)) { Thread.Sleep(500); } if (System.Diagnostics.Process.GetProcessesByName("HandBrakeCLI").Length != 0) { Thread.Sleep(500); } else { //hbOptions hbCl = new hbOptions(); //hbCli = hbCl.HbCliOptions(); if (textBox3.Text != "") { hbCli = textBox3.Text.ToString(); } else { hbCli = "-e x264 -q 20 -B 160"; } string t = e.Name; string s = t.Substring(0, t.Length - 4); //TODO: fix this its not reliable file = e.FullPath; string opath = textBox1.Text.ToString(); cmd = "-i \"" + file + "\" -o \"" + opath + "\\" + s + ".mp4\" " + hbCli; try { for (int i = 0; i < Ext.Count(); i++) { if (e.Name.Contains(Ext[i])) { Process hb = new Process(); hb.StartInfo.FileName = "D:\\Apps\\Handbrake\\Install\\Handbrake\\HandBrakeCLI.exe"; hb.StartInfo.Arguments = cmd; notifyIcon.BalloonTipTitle = "Now Converting"; notifyIcon.BalloonTipText = file; notifyIcon.ShowBalloonTip(2000); hb.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void button1_Click(object sender, EventArgs e) //ok button { //add each array item to the list for (int i = 0; i < filter.Count(); i++) { Ext.Add(filter[i]); } if (textBox1.Text != "" && textBox1.Text.Length > 2) { Watcher(); //call watcher to run } this.WindowState = FormWindowState.Minimized; } private void button2_Click(object sender, EventArgs e) //browse button { //broswe button DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } } private void button3_Click(object sender, EventArgs e) //commands button { Process np = new Process(); np.StartInfo.FileName = "notepad.exe"; np.StartInfo.Arguments = "hbCLI.txt"; np.Start(); } private void button4_Click(object sender, EventArgs e) //options button { hbOptions options = new hbOptions(); options.ShowDialog(); } private void button5_Click(object sender, EventArgs e) //exit button { this.Close(); } private void Form1_Load(object sender, EventArgs e) { this.Resize += Form_Resize; } } }

    Read the article

< Previous Page | 14 15 16 17 18 19  | Next Page >