Передача файлов веб-сервису.
От: orion_system  
Дата: 17.10.04 12:56
Оценка:
Добрый день.

Хотелось бы знать, как передать файл через интернет веб-сервису для
дальнейшего сохранения его на жестком диске.

Пример не помешал бы.

Спасиба.
Передача файлов веб-сервису.
От: Аноним  
Дата: 17.10.04 13:11
Оценка:
WebService :

[WebMethod]
public void PutExcelFile(string filename,byte[] b)
{
if (filename!=null && b!=null)
{
using (FileStream fsWrite = new FileStream(@"C:\Dokumente und Einstellungen\xxx\Eigene Dateien\Visual Studio Projects\csharp\office\ExcelWS\"+filename,FileMode.Create,FileAccess.ReadWrite))
{
fsWrite.Write(b,0,b.Length);
fsWrite.Flush();
}
}
}

--------------------------------------------------------------------------

WSClient

protected void ThisWorkbook_BeforeClose(ref bool Cancel)
{
byte[] b = null;
string fullname = thisWorkbook.FullName+".xml";
string shortname = thisWorkbook.Name;
if (fullname!=null && fullname!=string.Empty)
{
this.thisWorkbook.SaveCopyAs(fullname);
FileStream fsRead =null;
try
{
fsRead = new FileStream(fullname,FileMode.Open,FileAccess.Read);
b = new byte[fsRead.Length];
while (fsRead.Read(b,0,b.Length) > 0);
ExcelWS.ExcelWS proxy = new ExcelWS.ExcelWS();
proxy.PutExcelFile(shortname,b);
}
catch(Exception ex)
{
string s = ex.Message+"\n";
s+=ex.StackTrace;
}
finally
{
if (fsRead!=null) fsRead.Close();
}
}
Cancel = false;
}

-- Это всё мое личное мнение которое может не совпадать с Вашим или может быть ошибочным --
.NetCoder


данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение
Re: Передача файлов веб-сервису.
От: _orion_  
Дата: 17.10.04 13:19
Оценка:
А подругому можно?
Слышал про DIME Attachments. Но что это и как его использовать я не знаю.
Re[2]: Передача файлов веб-сервису.
От: Gollum Россия  
Дата: 17.10.04 13:23
Оценка:
Здравствуйте, _orion_, Вы писали:

__>А подругому можно?

__>Слышал про DIME Attachments. Но что это и как его использовать я не знаю.

http://www.google.ru/search?hl=ru&q=DIME+Attachments&lr=

Первая ссылка

Sending Files, Attachments, and SOAP Messages Via Direct Internet Message Encapsulation
У нас "два" по всем наукам, но ботанику мы знаем на "пять"!
Eugene Agafonov on the .NET

Re: §±§Ц§в§Ц§Х§С§й&#
От: Аноним  
Дата: 17.10.04 13:37
Оценка:
У IE кодировка слетела, а повторяться ломает. Короче, DIME + WSE это не сахар.

Вот то что сделано с WSE (DIME/Encryption)

WEB-Service

[WebService(Namespace="http://www.mydotnet.org")]
public class EmployeeServiceCom : System.Web.Services.WebService, IPasswordProvider
{
public EmployeeServiceCom()
{
InitializeComponent();
}
private DataTable ServiceUsers
{
get { return (DataTable) Application["USERS"];}
}

[WebMethod(Description="Employee aus der Datenbank Northwind mit SchlЁ№ssel id")]
public XmlNode LoadEmployeeByID(int id)
{
Authenticate(); // prЁ№fen ob gЁ№ltiger Aufruf
// access via enterprise service
EmployeeManager.EmployeeManager manager = new EmployeeManager.EmployeeManager();
DataSet ds = manager.CreateEmployeeByID(id);
DataTable employeeTable = ds.Tables["EMPLOYEE"];
if (employeeTable!=null)
{
foreach(DataRow row in employeeTable.Rows)
{
Employee employee = new Employee(row);
// get response context
SoapContext context = HttpSoapContext.ResponseContext;
// SchlЁ№ssel zum verschlЁ№sseln der Daten erzeugen
// add key for encryption
//EncryptedData data = new EncryptedData(CreateEncryptionKey());
// add encryption filter
//context.Security.Elements.Add(data);
// Attachment fЁ№r diesen employee anfЁ№gen
MemoryStream stream = new MemoryStream(employee.Photo);
employee.Photo=null;
// add attachment (the bitmap)
context.Attachments.Add(new DimeAttachment("image/OLE-Bitmap",TypeFormatEnum.MediaType,stream));
XmlNode node = Employee.ToXml(employee);
string s = node.InnerXml;
return node;
}
}
return null;
}
// --- IPasswordProvider Member ---
public string GetPassword(UsernameToken token)
{
EmployeeManager.ServiceUserManager manager = new ServiceUserManager();
DataSet ds = manager.LoadServiceUser(token.Username);
DataTable table = ds.Tables["SERVICEUSERS"];
foreach (DataRow row in table.Rows)
{
return (string) row["Password"];
}
return null;
}
private void Authenticate()
{
SoapContext context = HttpSoapContext.RequestContext;
if (context!=null && context.Security.Tokens.Count>0)
{
foreach(SecurityToken token in context.Security.Tokens)
{
if (token is UsernameToken) return;
}
}
throw new SecurityFormatException("no valid token");
}
// Key is unique and must exists on clientside identically
private EncryptionKey CreateEncryptionKey()
{
TripleDESCryptoServiceProvider des3 = new TripleDESCryptoServiceProvider();
des3.Key = new byte [] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
des3.IV = new byte [] {1,2,3,4,5,6};
SymmetricEncryptionKey Key = new SymmetricEncryptionKey(des3);
KeyInfoName KeyName = new KeyInfoName();
KeyName.Value="Northwind";
Key.KeyInfo.AddClause(KeyName);
return Key;
}

--- §Х§а§Т§С§У§Э§с§Ц§д§г§с §У web.config

<webServices>
<soapExtensionTypes>
<add type="Microsoft.Web.Services.WebServicesExtension, Microsoft.Web.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="1" group="0" />
</soapExtensionTypes>
</webServices>
</system.web>
<microsoft.web.services>
<security>
<passwordProvider type="EmployeeServiceCom.EmployeeServiceCom, EmployeeServiceCom" />
</security>
</microsoft.web.services>


Client

private void OnGetButtonClick(object sender, System.EventArgs e)
{
if (employeeIdTextBox.Text!=null && employeeIdTextBox.Text!=string.Empty)
{
EmployeeServiceCom.EmployeeServiceComWse employeeService = new EmployeeServiceCom.EmployeeServiceComWse();
UsernameToken token = new UsernameToken(userNameTextBox.Text,passwordTextBox.Text,PasswordOption.SendHashed);
employeeService.RequestSoapContext.Security.Tokens.Add(token);
XmlNode employeeNode = employeeService.LoadEmployeeByID(int.Parse(employeeIdTextBox.Text));
if (employeeNode!=null)
{
Employee employee = Employee.FromXml(employeeNode);
employeeListBox.Items.Clear();
employeeListBox.Items.Add(string.Format("ID: {0}", employee.ID));
employeeListBox.Items.Add(string.Format("{0} {1}", employee.Firstname, employee.Lastname).Trim());
employeeListBox.Items.Add(employee.Address);
employeeListBox.Items.Add(string.Format("Born: {0}", employee.BirthDate.ToShortDateString()));
employeeListBox.Items.Add(string.Format("{0} {1}", employee.Postalcode, employee.City).Trim());
employeeListBox.Items.Add("--------------------------");
employeeListBox.TopIndex = employeeListBox.Items.Count — 1;

SoapContext context = employeeService.ResponseSoapContext;
if (context.Attachments.Count > 0)
{
DimeAttachment att = context.Attachments[0];
employee.Photo= new byte[att.Stream.Length];
att.Stream.Read(employee.Photo,0,employee.Photo.Length);
employeePictureBox.Image = Image.FromStream(new MemoryStream(employee.Photo,78,employee.Photo.Length-78));
}
employeeIdTextBox.Focus();
employeeIdTextBox.SelectAll();

}
}
}

--- app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="microsoft.web.services" type="Microsoft.Web.Services.Configuration.WebServicesConfiguration, Microsoft.Web.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<appSettings>
<add key="EmployeeServiceComWinClient.EmployeeServiceCom.EmployeeServiceCom" value="http://localhost/EmployeeServiceCom/Main.asmx" />
</appSettings>
<microsoft.web.services>
<security>
<!--decryptionKeyProvider type="EmployeeServiceComWinClient.DecryptionProvider, EmployeeServiceComWinClient" / -->
</security>
</microsoft.web.services>
</configuration>


Пример естественно не полный, и являлся не более чем тестом для WSE 1.0

-- Это всё мое личное мнение которое может не совпадать с Вашим или может быть ошибочным --
.NetCoder


данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение
Re[2]: &#167;&#177;&#167;Ц&#167;в&#167;Ц&#167;Х&#167;С&#167;
От: MY Украина  
Дата: 18.10.04 13:44
Оценка:
А как реализовать Dime Attachments если обьем файла слишком большой?
Данный метод вебсервиса раотает для небольших файлов.
[WebMethod]
public void GetFileDime(string filename)
{
FileStream fs = File.Open(filename,FileMode.Open);
DimeAttachment da = new DimeAttachment("PDF", TypeFormat.MediaType, fs);
ResponseSoapContext.Current.Attachments.Add(da);
}

Для больших получаю:
Microsoft.Web.Services2.Dime.DimeFormatException: WSE352: The size of the record uuid:1ad7cd2f-10c9-4f24-a328-62fc3de4e117 exceed its limit.
Re[2]: &#167;&#177;&#167;Ц&#167;в&#167;Ц&#167;Х&#167;С&#167;
От: Аноним  
Дата: 18.10.04 13:52
Оценка:
Попробуй установить maxRequestLength в web.config

<system.web>
<httpRuntime maxRequestLength="16384" />
</system.web>

-- Это всё мое личное мнение которое может не совпадать с Вашим или может быть ошибочным --
.NetCoder


данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение
Re[3]: &#167;&#177;&#167;Ц&#167;в&#167;Ц&#167;Х&#167;С&#167;
От: MY Украина  
Дата: 18.10.04 14:04
Оценка:
А>Попробуй установить maxRequestLength в web.config


Пробовал. Сначала у меня эта проблема возникала когда я работал с
методом принимающим(возвращающим) byte[]

<system.web>
<httpRuntime maxRequestLength="639000000" useFullyQualifiedRedirectUrl="true" executionTimeout="45" />
</system.web>

Это помогло.
А для WSE 2.0 + Dime Attachments не канает...
Мне кажется что тут надо пробовать файл на chunks разбивать. Но нигде не могу найти примеров кода, как это делаеться.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.