quick_recipes (779892), страница 30

Файл №779892 quick_recipes (Symbian Books) 30 страницаquick_recipes (779892) страница 302018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 30)

The code snippet above does the reverse, by getting the actualfile system path of the URI given. Unlike the CreateXyzFileUriL()methods, GetFileNameL() actually resolves the filename by looking itup in the physical file system; if the file specified by the URI does notexist, it leaves with KErrNotFound.4.3.7 Advanced Recipes4.3.7.1Retrieve HTTP Proxy InformationAmount of time required: 20 minutesLocation of example code: \HTTP\HTTPConnectionConfigurationRequired library(s): commsdat.lib170SYMBIAN C++ RECIPESRequired header file(s): metadatabase.h, commsdattypeinfov1_1.h, commsdattypesv1_1.hRequired platform security capability(s): NoneProblem: You need to retrieve the HTTP proxy information.Solution: Read proxy server address and port information from CommsDatusing ‘priming’ search technique.#include <metadatabase.h> // CMDBSession#include <commsdattypeinfov1_1.h> // CCDIAPRecord, CCDProxiesRecord#include <commsdattypesv1_1.h> // KCDTIdIAPRecord, KCDTIdProxiesRecordvoid CGetProxyInfo::ProxyServerL(TInt aIAPId, TDes& aProxyServer){// Create session to CommsDat firstCommsDat::CMDBSession* dbs =CMDBSession::NewLC(CMDBSession::LatestVersion());// Load the IAP with record id aIAPIdCCDIAPRecord* iap = static_cast<CCDIAPRecord*>(CCDRecordBase::RecordFactoryL(KCDTIdIAPRecord));CleanupStack::PushL(iap);iap->SetRecordId(aIAPId);iap->LoadL(*dbs);// Read service table id and service type// from the IAP record foundTUint32 serviceId = iap->iService;RBuf serviceType;serviceType.CreateL(iap->iServiceType);CleanupClosePushL(serviceType);// Create a recordset of type CCDProxiesRecord// for priming search.// This will ultimately contain record(s)// matching the priming record attributesCMDBRecordSet<CCDProxiesRecord>* proxyRecords = new(ELeave)CMDBRecordSet<CCDProxiesRecord>(KCDTIdProxiesRecord);CleanupStack::PushL(proxyRecords);// Create the priming record and set attributes// that will be the search criteriaCCDProxiesRecord* primingProxyRecord =static_cast<CCDProxiesRecord*>(CCDRecordBase::RecordFactoryL(KCDTIdProxiesRecord));CleanupStack::PushL(primingProxyRecord);primingProxyRecord->iServiceType.SetMaxLengthL(serviceType.Length());primingProxyRecord->iServiceType = serviceType;primingProxyRecord->iService = serviceId;primingProxyRecord->iUseProxyServer = ETrue;// Append the priming record to the priming recordsetproxyRecords->iRecords.AppendL(primingProxyRecord);// Ownership of primingProxyRecord is transferred to// proxyRecords, just remove it from the CleanupStackNETWORKING171CleanupStack::Pop(primingProxyRecord);// All done!// Now to find a proxy table matching our criteriaif (proxyRecords->FindL(*dbs)){// Use the first record foundCCDProxiesRecord* proxyRecord = static_cast<CCDProxiesRecord*>(proxyRecords->iRecords[0]);// Get proxy server nameTPtrC serverName(proxyRecord->iServerName);if (serverName.Length() == 0){User::Leave(KErrNotFound);}// Get port numberTInt port = proxyRecord->iPortNumber;// Finally, create buffer in the form of// proxy_server_name:port formataProxyServer.Zero();aProxyServer.Append(serverName);aProxyServer.Append(':');aProxyServer.AppendNum(port);}else{// Didn’t find a proxy table with// specified service type, id and proxy attribute setUser::Leave(KErrNotFound);}// dbs, iap, serviceType, proxyRecordsCleanupStack::PopAndDestroy(4);}Discussion: CommsDat stores proxy information in the CCDProxiesRecord table (see commsdattypesv1_1.h), which along with servername and port number, stores service information, linking it to a servicetable.

By loading the IAP, given by aIAPId, we retrieve the associatedservice table name and id for our IAP, which we subsequently use toperform a ‘priming’ search on the proxy records to get the matching proxyrecord.4.3.8 Resources• Symbian OS Communications Programming, 2nd Edition: developer.symbian.com/commsbook.• Symbian Developer Library:◦ Symbian OS Guide > Communications Infrastructure > CommDb.172SYMBIAN C++ RECIPES◦ Symbian OS Guide > Communications Infrastructure > UsingSockets Server (ESOCK).◦ Symbian OS Guide > Networking > Using TCP/IP (INSOCK).◦ Symbian OS Guide > Networking > Using Secure Sockets (TLS).◦ Symbian OS Guide > Application Protocols > Using HTTP Client.◦ Symbian OS Guide > Application Protocols > Using InetProtUtils.4.4 MessagingThe ability to send and receive information in asynchronous forms,such as text messaging, multimedia messaging and email, has becomea key feature of modern mobile phone communications.

The ability tocommunicate with someone via phone or computer, without requiringthem to be available at the time, has become very popular. Growingwith this worldwide trend, messaging has evolved to make use of themultimedia capabilities of today’s phones, providing users with evenmore ways to communicate.Messaging can be an efficient and cheap form of mobile communication, as it is only necessary to connect to the network while amessage is actually being transmitted or received.

This has made it aparticularly suitable candidate for relatively infrequent (‘bursty’) streamsof communication, such as traffic updates or automatic reporting ofmedical data.Messages are easy to store for future reference, it is a simple task to senda message more than once, or to more than one recipient, or to schedulethe sending of a message. Such functionality is not so readily availablewith a synchronous means of communication, such as a phone call.4.4.1 Supported BearersSymbian provides support for:• Short Message Service (SMS, also known as text messaging).• Multimedia Message Service (MMS).• Post Office Protocol version 3 (POP3) for receiving email.• Internet Message Access Protocol version 4 (IMAP4) for receivingemail.• Simple Mail Transfer Protocol (SMTP) for sending email.They all require a connection to an operator’s network, and in the caseof email, the Internet, when sending or receiving messages.MESSAGING173Symbian provides support for receiving Cell Broadcast and Unstructured Supplementary Service Data (USSD).

There is also a ‘BIO messaging’component for handling messages which are meant to update some aspectof the device, such as vCards, vCalendars, over-the-air configuration messages and Nokia Smart Messages. All of these areas are outside the scopeof this book.Symbian has abstracted the common functionality into a client–servermessaging subsystem, which exposes a framework API for receiving,sending, creating and manipulating messages.

The message server manages access to the different transports via a plug-in architecture, as wellas the Symbian OS message store.In the messaging plug-in architecture, each protocol bearer is represented by a client Message Type Module (MTM).4.4.2 SendAsSince it is not guaranteed that all bearers will be available on everySymbian phone, Symbian provides the SendAs server, which allowsapplications to dynamically discover and choose a message type that isappropriate for their data, based on the transports available; the SendAsserver will then create and send the message for you.The SendAs server is described in more detail in the Sending Messageschapter of the Symbian Press book by Iain Campbell, Symbian OSCommunications Programming, 2nd Edition.

In these recipes, we showyou how to use the message server itself to add email, SMS or MMSmessaging to your application.4.4.3 ServicesThe purpose of a service is to handle communications, via lower-levelcomms components such as Telephony and Networking, with an externalmessaging service provider (known as a remote service); for example,sending an SMS to a Short Message Service Center (SMSC), or receivingemails from a mailbox on a POP3 server. A remote service is frequentlyassociated with a remote store – for instance, the SIM’s SMS store, or auser’s email server mailbox.

There is also a local service which managesoperations performed on the phone’s message store itself, such as readingor deleting messages.4.4.4 The Message Store4.4.4.1Structure and Main ClassesIn the Symbian OS message store, messages, folders and services areorganized in a tree structure, as shown in Figure 4.4.1. The tree’s nodes, orentries, are accessible to message server clients through the CMsvEntry174SYMBIAN C++ RECIPESRoot entryLocal(service entry)Global Outbox(folder entry)Global Inbox(folder entry)Email (POP3)(service entry)Email (POP3)(service entry)Email (IMAP)(service entry)Email message(messageentry)Email message(messageentry)Email message(messageentry)AttachmententryEmail message(messageentry)MMS message(messageentry)SMS message(messageentry)Email message(messageentry)AttachmententrySMS message(messageentry)Email message(messageentry)Email message(messageentry)SMS message(messageentry)SMS(service entry)MMS(service entry)SMS message(service entry)-Stored on SIMAttachmententryFigure 4.4.1 Simplified Version of the Contents of a Typical Message Storeclass.

Характеристики

Тип файла
PDF-файл
Размер
1,59 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6513
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее