powered by simpleCommunicator - 2.0.46     © 2025 Programmizd 02
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / Создание БД через WCF-сервис
25 сообщений из 61, страница 2 из 3
Создание БД через WCF-сервис
    #38570800
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

примерно так (код я не проверял, у меня нет MS SQL):
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
public void InsertFile(string fileName)
{
	if (!File.Exists(fileName)) return;
	using(var stream = File.OpenRead(fileName))
	{
		using(var connection = new SqlConnection("connection string"))
		{
			connection.Open();
			using(var transaction = connection.BeginTransaction(IsolationLevel.ReadCommited))
			{
				using(var command = new SqlCommand(connection, @"insert into MyFileTable (file_guid, file_content) 
																 output INSERTED.file_content.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT()
																 values (@file_guid, @file_content)"))
				{
					command.Parameters.AddWithValue("@file_guid", Guid.NewGuid());
					command.Parameters.AddWithValue("@file_content", new byte[0]);
					
					using(var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var path = reader.GetString(0);
							var transactionContext = reader.GetSqlBytes(1).Buffer;

							using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write))
							{
								var buffer = new byte[10 * 1024 * 1024]; //buffer size = 10 MB;
								var readed = 0;
								while((readed = stream.Read(buffer, 0, buffer.Length)) != 0)
								{
									fileStream.Write(buffer, 0, readed);
									fileStream.Flush();
								}
							}
						}
					}
					
				}
				
				transaction.Commit();
			}
		}
	}
}



возможно такой output: "output INSERTED.file_content.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT()" не поддерживается. тогда надо сделать insert (или insert с output inserted.[поле ID], если ID строки генерится в базе), а потом "select file_content.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from Table where [поле ID] = ID"
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570817
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Забыл транзакцию в команде указать.
var command = new SqlCommand("... text ...", connection, transaction);
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570861
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch,
SqlExeption was unhandled:
Cannot find either column "Photos" or the user-defined function or aggregate "Photos.PathName", or the name is ambiguous.

в колонке Photos - данные varbinary.
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570872
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
разобралась
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570882
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch,
а это нормально, что 1,5-гигабайтный файл скинуло за 10 секунд и он отображается так как на картинке?
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570886
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

нет конечно, пройдитесь отладчиков вот тут:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
using(var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var path = reader.GetString(0);
							var transactionContext = reader.GetSqlBytes(1).Buffer;

							using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write))
							{
								var buffer = new byte[10 * 1024 * 1024]; //buffer size = 10 MB;
								var readed = 0;
								while((readed = stream.Read(buffer, 0, buffer.Length)) != 0)
								{
									fileStream.Write(buffer, 0, readed);
									fileStream.Flush();
								}
							}
						}
					}
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570900
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
LelouchDessi,

нет конечно, пройдитесь отладчиков вот тут:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
using(var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var path = reader.GetString(0);
							var transactionContext = reader.GetSqlBytes(1).Buffer;

							using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write))
							{
								var buffer = new byte[10 * 1024 * 1024]; //buffer size = 10 MB;
								var readed = 0;
								while((readed = stream.Read(buffer, 0, buffer.Length)) != 0)
								{
									fileStream.Write(buffer, 0, readed);
									fileStream.Flush();
								}
							}
						}
					}


вы были правы... if (reader.Read()) дает false, и запись не происходит вообще
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570902
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

в запросе output есть ?
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570903
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch, да
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570904
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch,
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
public void InsertFile(string fileName)
        {
            if (!File.Exists(fileName)) return;
            using (var stream = File.OpenRead(fileName))
            {
                using (var connection = new SqlConnection("Server=localhost;initial catalog=FileServiceDB;integrated security=SSPI"))
                {
                    connection.Open();
                    using (var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                    {
                        using (var command = new SqlCommand("insert into employees (EmployeeID, Photos, RowGuid) output INSERTED.Photos.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() values ('2', @file_content, @file_guid)", connection, transaction))
                        {
                            command.Parameters.AddWithValue("@file_content", new byte[0]);
                            command.Parameters.AddWithValue("@file_guid", Guid.NewGuid());
                            

                            using (var reader = command.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    var path = reader.GetString(0);
                                    var transactionContext = reader.GetSqlBytes(1).Buffer;

                                    using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write))
                                    {
                                        var buffer = new byte[10 * 1024 * 1024]; //buffer size = 10 MB;
                                        var readed = 0;
                                        while ((readed = stream.Read(buffer, 0, buffer.Length)) != 0)
                                        {
                                            fileStream.Write(buffer, 0, readed);
                                            fileStream.Flush();
                                        }
                                    }
                                }
                            }

                        }

                        transaction.Commit();
                    }
                }
            }
            MessageBox.Show("Done");
        }
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570906
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

скопируйте сюда код.
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570912
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Не вижу причину, почему reader.read возвращает false.
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570914
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch, я поменяла инициализацию данныхх с new byte[] на 0х00, и стало true.
Но, по-прежнему "записывало" за 10 секунд. Я стала дебагать, итераций 50 может прошло и выдало такое:
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570917
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
1) Вставка точно выполняется?
2) Попробуйте заменить на такое:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
public void InsertFile(string fileName)
{
	if (!File.Exists(fileName)) return;
	using(var stream = File.OpenRead(fileName))
	{
		using(var connection = new SqlConnection("connection string"))
		{
			connection.Open();
			using(var transaction = connection.BeginTransaction(IsolationLevel.ReadCommited))
			{
				var fileGuid = Guid.NewGuid();
				using(var command = new SqlCommand(@"insert into MyFileTable (file_guid, file_content) values (@file_guid, @file_content)", connection, transaction))
				{
					command.Parameters.AddWithValue("@file_guid", fileGuid);
					command.Parameters.AddWithValue("@file_content", new byte[0]);
					
					command.ExecuteNonQuery();
				}
				using(var command = new SqlCommand(@"select file_content.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from MyFileTable where file_guid = @file_guid", connection, transaction))
				{
					command.Parameters.AddWithValue("@file_guid", fileGuid);
					
					using(var reader = command.ExecuteReader())
					{
						if (reader.Read())
						{
							var path = reader.GetString(0);
							var transactionContext = reader.GetSqlBytes(1).Buffer;

							using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write))
							{
								var buffer = new byte[10 * 1024 * 1024]; //buffer size = 10 MB;
								var readed = 0;
								while((readed = stream.Read(buffer, 0, buffer.Length)) != 0)
								{
									fileStream.Write(buffer, 0, readed);
									fileStream.Flush();
								}
							}
						}
					}
					
				}
				
				transaction.Commit();
			}
		}
	}
}
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570918
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch, просто output убрать?
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570920
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

попробуйте убрать .Flush()
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570921
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Dessi,

ну раз у вас работает output, то уже не актуально.
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570925
Lelouch
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Кстати, судя по запросу... Это у кого у вас 1.5 гиговые фотографии? оО
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570928
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
LelouchКстати, судя по запросу... Это у кого у вас 1.5 гиговые фотографии? оО

та это просто название колонки такое))
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38570934
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Lelouch, заработало!
Я протестила на видео в 440 мб, всё отлично сохраняет, и тот сохраненный без расширения файл отлично открывается медиаплеером!

Теперь буду заниматься чтением из Бд... )))
спасибо Вам огромное!
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38583068
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Здравствуйте, форумчане. Работаю над следующим.
Есть WCF-сервис (описанный в данной теме), на сервисе происходит запись/скачивание файлов из БД.
Суть проблемы: всё чтение/запись происходит через стримы на серверной стороне. Мне же надо на клиентской стороне сделать прогрессБар с ходом выполнения закачки/загрузки. Никак не могу понять, как сделать отображение процесса, который происходит на сервере, на клиентской стороне. Все мозги сломала... Подскажите, пожалуйста. Спасибо!
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38583143
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
уже не актуально.
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38585204
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Здравствуйте, форумчане. Снова обращаюсь к вам за помощью.
Суть задания: скачать файл через wcf-сервис с удаленной БД.
Суть проблемы: небольшие файлы скачивает без проблем. А вот с файлами побольше - проблема. Выкидывает ексепшн.Тестила закачку одного и того же 1,5-гигабайтного файла, и ексепшн всегда в разные моменты: то через 900 мб закачки, то через 1,1гб, то через 1,4гб, то через 600 мб...вот ексепшн:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
System.IO.IOException was unhandled
  HResult=-2146232800
  Message=An exception has been thrown when reading the stream.
  Source=System.ServiceModel
  StackTrace:
       at System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at WpfClient.MainWindow.<>c__DisplayClass16.<DownloadMethod>b__12() in c:\Users\Administrator\Desktop\!New.Project\MyTest\FileServiceLib\WpfClient\MainWindow.xaml.cs:line 273
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.ServiceModel.CommunicationException
       HResult=-2146233087
       Message=The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:20:00'.
       Source=System.ServiceModel
       StackTrace:
            at System.ServiceModel.Channels.HttpInput.WebResponseHttpInput.WebResponseInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
            at System.ServiceModel.Channels.MaxMessageSizeStream.Read(Byte[] buffer, Int32 offset, Int32 count)
            at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
            at System.Xml.EncodingStreamWrapper.Read(Byte[] buffer, Int32 offset, Int32 count)
            at System.Xml.XmlBufferReader.TryEnsureBytes(Int32 count)
            at System.Xml.XmlBufferReader.GetBuffer(Int32 count, Int32& offset, Int32& offsetMax)
            at System.Xml.XmlUTF8TextReader.ReadText(Boolean hasLeadingByteOf0xEF)
            at System.Xml.XmlUTF8TextReader.Read()
            at System.Xml.XmlBaseReader.MoveToContent()
            at System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       InnerException: System.IO.IOException
            HResult=-2146232800
            Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
            Source=System
            StackTrace:
                 at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
                 at System.ServiceModel.Channels.PreReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
                 at System.ServiceModel.Channels.HttpInput.WebResponseHttpInput.WebResponseInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
            InnerException: System.Net.Sockets.SocketException
                 HResult=-2147467259
                 Message=An existing connection was forcibly closed by the remote host
                 Source=System
                 ErrorCode=10054
                 NativeErrorCode=10054
                 StackTrace:
                      at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
                      at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
                 InnerException: 



вот конфиг сервера:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
<?xml version="1.0"   encoding="utf-8"   ?>
<configuration>
  <system.transactions>
    <defaultSettings timeout="23:50:00"/>
  </system.transactions>
  <system.serviceModel>
        
      <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
    </diagnostics>
    <services>
      <service name="FileServiceLib.FileService"
      behaviorConfiguration="FileServiceMEXBehavior" >
        
        <endpoint address="" 
        binding="basicHttpBinding"
                  bindingConfiguration="customBinding"
        contract="FileServiceLib.IFileService" behaviorConfiguration="endpointBehavior" />
        
        <!-- Включить конечную точку МЕХ -->
        <endpoint address="mex"
        binding="mexHttpBinding"
        contract="IMetadataExchange"  />

        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:1825/FileService"  />
          </baseAddresses>
        </host>
      </service>
    </services>    
    <bindings>
      <basicHttpBinding>
        <binding name="customBinding"
                 
                 maxReceivedMessageSize="9223372036854775807"   
                
          maxBufferSize="2147483647"

          sendTimeout="24.20:31:23.6470000"
          closeTimeout="20:20:00"
          openTimeout="21:20:00"
          receiveTimeout="24.20:31:23.6470000"
          maxBufferPoolSize="2147483647"
          transferMode="Streamed" >
          <security mode="None">
            <transport clientCredentialType="None"  />
           
          </security>
          
        </binding>
      </basicHttpBinding>
      
    </bindings>
        <!--Определение поведения для МЕХ-->
    <behaviors>
      
      <endpointBehaviors>
        <behavior name="endpointBehavior">
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </endpointBehaviors>
    
      <serviceBehaviors>
        <behavior name="FileServiceMEXBehavior"  >
          <serviceDebug
            httpHelpPageEnabled="true"
            includeExceptionDetailInFaults="true"  />
          <serviceMetadata httpGetEnabled="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <connectionStrings>
    <add name="FileServiceDBEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=WIN-8PBNCAJO58P;initial catalog=FileServiceDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>



вот конфиг клиента:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
<configuration>
   
      <trace autoflush="true" />
        <sources>
            <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
                <listeners>
                    <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                        <filter type="" />
                    </add>
                    <add name="ServiceModelMessageLoggingListener">
                        <filter type="" />
                    </add>
                </listeners>
            </source>
            <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning,ActivityTracing">
                <listeners>
                    <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                        <filter type="" />
                    </add>
                    <add name="ServiceModelTraceListener">
                        <filter type="" />
                    </add>
                </listeners>
            </source>
          
          
            <source name="System.ServiceModel"
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
              <listeners>
                <add name="sdt"
                    type="System.Diagnostics.XmlWriterTraceListener"
                    initializeData= "SdrConfigExample.e2e" />
              </listeners>
            </source>
       
        </sources>
        <sharedListeners>
            <add initializeData="c:\users\administrator\desktop\!new.project\mytest\fileservicelib\wpfclient\app_messages.svclog"
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
                <filter type="" />
            </add>
            <add initializeData="c:\users\administrator\desktop\!new.project\mytest\fileservicelib\wpfclient\app_tracelog.svclog"
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
                <filter type="" />
            </add>
        </sharedListeners>
    </system.diagnostics>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.transactions>
    <defaultSettings timeout="23:50:00"/>
  </system.transactions>
  <system.serviceModel>

    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IFileService"
                 sendTimeout="24.20:31:23.6470000"
                 receiveTimeout="24.20:31:23.6470000"
                 openTimeout="24.20:31:23.6470000"
                 closeTimeout="24.20:31:23.6470000"
                 maxBufferSize="2147483647"
                 maxReceivedMessageSize="9223372036854775807"
                 maxBufferPoolSize="2147483647"
                 transferMode="Streamed">          
          <security mode="None">
            <transport clientCredentialType="None"  />
            
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:1825/FileService" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IFileService" contract="ServiceReference1.IFileService"
                behaviorConfiguration="endpointBehavior"
        name="BasicHttpBinding_IFileService" />
    </client>
   <behaviors>
    <endpointBehaviors>
      <behavior name="endpointBehavior">
        <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
      </behavior>
    </endpointBehaviors>
    </behaviors>
    
   
      <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
    </diagnostics>
    </system.serviceModel>
  <connectionStrings>
    <add name="FileServiceDBEntities"
         connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=WIN-8PBNCAJO58P;initial catalog=FileServiceDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>



вот сам метод закачки файла:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
public FileMessageContract GetFile(DownloadMessage request)
        {
            FileMessageContract result = new FileMessageContract();
            result.fileName = request.fileName;
            var connection = new SqlConnection("Server=localhost;initial catalog=FileServiceDB;integrated security=SSPI");
            connection.Open();
            var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
            using (var command = new SqlCommand("SELECT FileStream.PathName() FROM FilesTable Where FileName =@file_name and FolderID=@folder_id", connection, transaction))
            {
                command.Parameters.AddWithValue("@file_name", request.fileName);
                command.Parameters.AddWithValue("@folder_id", request.folderId);

                
                result.filePath = (string)command.ExecuteScalar();
               
                /*  command.CommandText = "SELECT DATALENGTH(FileStream) FROM FilesTable";
                  result.length = (long)command.ExecuteScalar();*/

                command.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        var transactionContext = reader.GetSqlBytes(0).Buffer;
                        Stream sqlFileStream = new SqlFileStream(result.filePath, transactionContext, FileAccess.Read);
                        result.length = sqlFileStream.Length;
                        result.fileStream = sqlFileStream;
                    }
                }
            }
            
            /*  transaction.Commit();
               connection.Close(); 
                connection.Dispose();
             transaction.Dispose();*/
            return result;
        }public FileMessageContract GetFile(DownloadMessage request)
        {
            FileMessageContract result = new FileMessageContract();
            result.fileName = request.fileName;
            var connection = new SqlConnection("Server=localhost;initial catalog=FileServiceDB;integrated security=SSPI");
            connection.Open();
            var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
            using (var command = new SqlCommand("SELECT FileStream.PathName() FROM FilesTable Where FileName =@file_name and FolderID=@folder_id", connection, transaction))
            {
                command.Parameters.AddWithValue("@file_name", request.fileName);
                command.Parameters.AddWithValue("@folder_id", request.folderId);

                
                result.filePath = (string)command.ExecuteScalar();
               
                /*  command.CommandText = "SELECT DATALENGTH(FileStream) FROM FilesTable";
                  result.length = (long)command.ExecuteScalar();*/

                command.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        var transactionContext = reader.GetSqlBytes(0).Buffer;
                        Stream sqlFileStream = new SqlFileStream(result.filePath, transactionContext, FileAccess.Read);
                        result.length = sqlFileStream.Length;
                        result.fileStream = sqlFileStream;
                    }
                }
            }
            
            /*  transaction.Commit();
               connection.Close(); 
                connection.Dispose();
             transaction.Dispose();*/
            return result;
        }



вот код скачивания файла со стороны клиента:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
 private void btnDownload_Click(object sender, RoutedEventArgs e)
        {    
            if (SelectedItem().Tag is FilesInfo)
            {
                var id = SelectedItem().Tag as FilesInfo;
                var name = SelectedItem().Header.ToString();
                Thread thread = new Thread(() => DownloadMethod(id, name));
                thread.Start();
            }
        }


public void DownloadMethod(FilesInfo id, string name)
        {
            var buffer = new byte[10 * 1024 * 1024];
            DownloadMessage downloadRequest = new DownloadMessage();
            downloadRequest.fileName = name;
            downloadRequest.folderId = id.FolderID;
            FileMessageContract fileMessage = new FileMessageContract();          
            FileStream fileStream = File.Open(@"C:\" + name, FileMode.Create);

            Thread thr = new Thread(new ThreadStart(() =>
            {
                var path = serviceClient.GetFile(ref downloadRequest.fileName, ref downloadRequest.folderId, out fileMessage.length, out fileMessage.fileStream);                                
                Dispatcher.Invoke(() =>
                {
                    progress.Maximum = fileMessage.length;
                    progress.Value = 0;
                    progress.Visibility = Visibility.Visible;
                });               
                var readed = 0;
          
                    while ((readed = fileMessage.fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fileStream.Write(buffer, 0, readed);
                        fileStream.Flush();                       
                        Dispatcher.Invoke(() =>
                        {
                            progress.Value = fileStream.Position;
                        });
                    }            
                Dispatcher.Invoke(() => { progress.Visibility = Visibility.Hidden; });
                MessageBox.Show("Your file was downloaded successfully. It saved on C:\\ drive.");
                fileMessage.fileStream.Dispose();
                fileStream.Dispose();
            }
            ));
            thr.Start();
        }



так же есть лог, но в нем те же в точности ошибки.
Не знаю что делать... помогите, пожалуйста!
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38585369
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
сделала лог ещё и для сервера... вот результат:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
Error trace record:

<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>524340</EventID>
<Type>3</Type>
<SubType Name="Error">0</SubType>
<Level>2</Level>
<TimeCreated SystemTime="2014-03-13T11:52:01.3705958Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{ee9e6942-ae5b-400c-8abd-c21e9b119791}" />
<Execution ProcessName="TestDB.vshost" ProcessID="4936" ThreadID="11" />
<Channel />
<Computer>WIN-8PBNCAJO58P</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.ServiceOperationExceptionOnReply.aspx</TraceIdentifier>
<Description>Replying to an operation threw a exception.</Description>
<AppDomain>TestDB.vshost.exe</AppDomain>
<Source>System.ServiceModel.Dispatcher.ImmutableDispatchRuntime/4878312</Source>
<Exception>
<ExceptionType>System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The handle is invalid.
</Message>
<StackTrace>
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.ReadCore(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.Data.SqlTypes.SqlFileStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider value)
at System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
at System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReplyCore(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpRequestContext.OnReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc&amp; rpc)
</StackTrace>
<ExceptionString>System.IO.IOException: The handle is invalid.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.ReadCore(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
   at System.Data.SqlTypes.SqlFileStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlDictionaryWriter.WriteValue(IStreamProvider value)
   at System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
   at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
   at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
   at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)



The handle is invalid? Но почему?? Какое-то время ж файл пишется... я в недоумении..
...
Рейтинг: 0 / 0
Создание БД через WCF-сервис
    #38585487
Dessi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я разобралась... Дело было в том, что конекшн и транзакшн в методе GetFile со временем попадали под сборку мусора, и попадали они до завершения чтения потока. Так как конекшн и транзакшн диспоузились во время чтения из стрима, программа вылетала с ошибкой, что соединение было принудительно закрыто.
РЕШЕНИЕ было таковым: чтоб конекшн и транзакшн не попадали под сборку мусора, я классе сервиса создала два приватных поля типа конекшн и транзакшн, а в методе GetFile присвоила в эти поля текущие конекшн и транзакшн. Таким образом сборщик мусора при проверке конекшн и транзакшн будет видеть, что на них кто-то ссылается и не будет делать диспоуз.
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
 public class FileService:IFileService
    {
        private static SqlConnection conn;
        private static SqlTransaction trn;
       
       ...
         
        public FileMessageContract GetFile(DownloadMessage request)
        {
            ...
            var connection = new SqlConnection("Server=localhost;initial catalog=FileServiceDB;integrated security=SSPI;Connection Timeout=65536");
            connection.Open();
            conn = connection;            
            var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
            trn = transaction;



Во-вторых, я изменила ServiceBehavior таким образом, чтобы для каждого сеанса(сессии) создавался свой экземпляр сервиса - один на всю сессию:
Код: c#
1.
2.
3.
4.
5.
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class FileService:IFileService
    {
        private static SqlConnection conn;
        private static SqlTransaction trn;


и... всё заработало! =)
...
Рейтинг: 0 / 0
25 сообщений из 61, страница 2 из 3
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / Создание БД через WCF-сервис
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]