Михаил Голованов
В прошлом номере журнала я писал о реализации модели Briefcase с помощью ADO. В отличие от ADO, средства работы с отключенными наборами данных в MIDAS были реализованы с самой первой версии. Реализация модели Briefcase средствами MIDAS несколько проще, хотя и здесь есть свои подводные камни.
Приложение MIDAS состоит из двух частей: сервера приложений и тонкого клиента. Сервер приложений «общается» с сервером БД (или другим источником данных), реализует бизнес-правила и предоставляет тонкому клиенту данные по запросу. Функция тонкого клиента – это отображение данных пользователю.
В качестве примера мы спроектируем простой сервер приложений и тонкий клиент для работы с базой, описанной в предыдущей части статьи. Сервер приложений реализуем как модуль MTS/COM+. Никаких особенностей создания сервера приложений для модели briefcase нет, поэтому я не буду описывать этот процесс в деталях. В IDE Delphi создадим новый проект приложения для MTS/COM+, выбрав пункт меню File/New/Other, и в появившемся диалоге выберем пункт ActiveX Library с закладки ActiveX. Затем включим в проект новый удаленный модуль данных (File/New/Other и пункт Transactional Datamodule с закладки Multitier).
В удаленном модуле данных разместим следующие компоненты и установим значения их свойств согласно таблице 1, приведенной ниже.
Компонент | Свойство | Значение |
Conn:TADOConnection | ConnectionString | Настроить на соединение с БД |
adsParams:TADODataSet | Connection | Conn |
CommandText | CommandText | select * from Params |
dspParams:TDataSetProvider | DataSet | adsParams |
Таблица 1
Откомпилируйте проект сервера и установите полученную dll в новое MTS/COM+-приложение c именем MIDAS_briefcase, с помощью пункта меню Run/Install COM+ Object.
Тонкий клиент представляет собой DeskTop-приложение. Для связи с сервером приложений клиент использует один из компонентов типа Connection с закладки DataSnap (мы воспользуемся DCOMConnection) и специальный DataSet – ClientDataSet.
В таблице 2 приведены свойства, влияющие на работу компонентов тонкого клиента с сервером приложений, а также их значения.
Компонент | Свойство | Значение |
DCOMConn:TDCOMConnection | ServerName | Project1.MIDAS_bc |
| LoginPrompt | false |
cdsParams:TClientDataSet | RemoteServer | DcomConn |
| ProviderName | dspParams |
Таблица 2
Внешний вид формы приложения тонкого клиента приведен на рисунке 1.
Рисунок 1
Получение данных с центрального сервера
Получение данных с сервера приложений аналогично приведенному в примере для ADO. Код приведен ниже.
procedure TForm1.act_RemoteConnectExecute(Sender: TObject); begin try with cdsParams do try Close; RemoteServer:=DCOMConn; FileName:=''; Active:=true; except on E:Exception do MessageDlg(Format('Ошибка подключения к серверу: %s', [E.Message]), mtError, [mbOk], 0); end; finally DCOMConn.Close; end; |
Все просто, но для подключения к серверу надо не забывать сбрасывать имя файла кэша (свойство FileName) и закрывать соединение с сервером после получения данных.
Чтение и запись данных из локального кэша
Для чтения данных из локального кэша у ClientDataSet есть метод LoadFromFile:
procedure TForm1.act_ConnectLocalExecute(Sender: TObject); begin with cdsParams do begin RemoteServer:=nil; FileName:=ExtractFilePath(Application.ExeName) + LocalFile; LoadFromFile(FileName); end; end; |
Для записи в локальный кэш – метод SaveToFile:
with cdsParams do SaveToFile(ExtractFilePath(Application.ExeName) + LocalFile); |
Опять же никаких сюрпризов.
Сохранение данных на сервер, отмена сделанных изменений
Для сохранения данных на сервер предназначен метод CilentDataSet-а ApplyUpdates. Параметр данного метода указывает макисимально допустимое количество ошибок при передаче данных на сервер.
procedure TForm1.act_SaveToServerExecute(Sender: TObject); begin if cdsParams.Active and (cdsParams.ApplyUpdates(0) = 0) then act_RemoteConnect.Execute; end; |
При возникновении ошибки генерируется событие OnReconcileError. Обработка ошибки осуществляется с помощью стандартного модуля обработчика ошибки, подключить этот модуль в проект можно, выбрав ReconcileErrorDialog на закладке Dialogs (File/New/Other). Обработчик OnReconcileError будет выглядеть при этом следующим образом:
procedure TForm1.cdsParamsReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin Action:=HandleReconcileError(DataSet, UpdateKind, E); end; |
Для отмены внесенных изменений ClientDataSet содержит метод CancelUpdates.
Чтение данных «порциями»
Обмен данных между тонким клиентом и сервером приложений происходит пакетами. Пакет содержит информацию о метаданных и/или набор записей. Интересной возможностью MIDAS является передача данных «порциями». Естественно, данная возможность реализуется лишь во время наличия соединения с центральным сервером. Включение данной возможности осуществляется установкой свойства FetchOnDemand ClientDataset-а в true. К сожалению, даже при этом запрос к серверу базы данных выбирает все записи сразу. Об одном из способов устранения этого недочета я и хочу рассказать.
Первое, что необходимо сделать, это изменить текст SQL-запроса, находящегося в свойстве CommandText компонента adsParams (напомню, что это ADODataSet), на следующий:
select Top 2 * from Params where ParamID > :ID |
При этом записи будут выбираться порциями по 2. Естественно, что в реальных приложениях размер пакета будет больше этого числа. Конкретное число представляет собой компромисс между затратами времени на передачу пакета по сети (чем больше размер пакета, тем выше задержки при его передаче) и задержками, возникающими от частого обращения с запросами к серверу БД. (на практике размер такого пакета зависит от размера записи, но в среднем составляет от 30 до 250 строк. – прим.ред.)
Остается решить проблему, как клиент будет передавать серверу идентификатор последней считанной записи (ParamID). Проблема эта возникает потому, что сервер приложений не сохраняет состояние между вызовами клиентов. С одной стороны, это делает сервер приложений более масштабируемым, но с другой, требует дополнительного кода на стороне клиента для хранения состояния.
Для передачи значения первичного ключа последней прочитанной клиентом записи можно использовать событие BeforeGetRecords. Данное событие определено для набора данных ClientDataSet на клиенте и компонента провайдера на сервере. Перед получением пакета с записями это событие сначала генерируется на клиенте, а затем у провайдера на сервере приложений. Событие имеет параметр, передаваемый по ссылке OwnerData (типа OleVariant). Вот через этот параметр мы и будем передавать значение ключа последней записи. Код обработчика в клиентском приложении:
procedure TForm1.cdsParamsBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); begin if not cdsParams.FieldByName('ParamID').IsNull then OwnerData:=cdsParams.FieldByName('ParamID').Value; end; |
Соответственно для провайдера на сервере приложений:
procedure TMIDAS_bc.dspParamsBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant); begin if not VarIsNull(OwnerData) and not VarIsClear(OwnerData) then adsParams.Parameters.ParamValues['ID']:=OwnerData; end; |
Чтобы инициировать подкачку, необходимо обрабатывать еще одно событие объекта ClientDataSet – OnScroll:
procedure TForm1.cdsParamsAfterScroll(DataSet: TDataSet); begin if cdsParams.Eof then cdsParams.GetNextPacket; end; |
Вызов cdsParams.GetNextPacket; как раз и инициирует получение следующего пакета данных.
Как выяснилось, код метода GetNextPacket содержит ошибку, выражающуюся в отказе чтения следующего пакета после нескольких попыток чтения первого пакета. Связано это с неправильным значением переменной ProviderEOF в описанной выше ситуации.
function TCustomClientDataSet.GetNextPacket: Integer; begin CheckActive; if ProviderEOF then Result := 0 else begin UpdateCursorPos; if (FPacketRecords = 0) and FMasterLink.Active and (FMasterLink.Fields.Count > 0) then CheckDetailRecords else begin AddDataPacket(DoGetRecords(FPacketRecords, Result, 0, '', Unassigned), Result <> FPacketRecords); ProviderEOF := Result <> FPacketRecords; end; Resync([]); end; end; |
Исправлено это было явным присвоением ProviderEOF значения false перед выполнением проверки if ProviderEOF then Result := 0 else …...
Вышеописанный метод организации подкачки имеет, к сожалению, один большой недостаток – он будет работать лишь при сортировке набора данных на клиенте по первичному ключу. Однако не так сложно доработать его для обхода и этой проблемы.
Другие работы по теме:
Английский, домашнее чтение, 2 часть. Билеты
Билет № Theme 35. "The Dead" - J. Joyce In "The Dead" all the themes of the "Dubliners" are mentioned. Name them. How did Dublin's portrait in "The Dead" differ from the description of the city in the other stories?
Английский, домашнее чтение, билеты
Экзаменационный билет по предмету ПКОЯз. АНГЛ. ДОМАШНЕЕ ЧТЕНИЕ Билет № W. S. Maugham “The Art the Grasshopper” Explain the title of the story.
Curious George And The Man In The
Yellow Hat Essay, Research Paper Through Thick and Thin Friends are appreciated the most in times of need. They calm you down when you are stressed and comfort you when you cry but first and foremost they are there when you get in trouble. A couple of friends that are shining examples of sticking together in times of trouble are Curious George and the Man in the Yellow Hat.
Something Strange Happens Ever Essay Research Paper
A man, Bob Johnson, leans on a cold, concrete pillar, silently waiting for the train to take him to work. He waits as he has waited for the past seven years of his monotonous, somewhat mechanical existence. He glances calmly at his wristwatch; thirty-seven minutes past eight o clock in the morning. Damn, he thinks to himself.
Invisible Man Essay Research Paper In the 2
Invisible Man Essay, Research Paper In the novel, The Invisible Man by Ralph Ellison, the narrator of the story, like Siddhartha and Antonius Blok, is on a journey, but he is searching to find himself. This is interesting because the narrator is looking for himself and is not given a name in the book. Like many black people, the narrator of the story faces persecution because of the color of his skin.
James Bond Vs Thoms Crown Essay Research
Paper Over the years, there has been a constant battle between various ?guy? movies for the title of the best. Each of these movies must contain a certain amount of toys, exciting lifestyles, and hot cars. The two that stand out most are James Bond and Thomas Crown. For many reasons James Bond is better.
Invisible Man Essay Research Paper The Narrator
Invisible Man Essay, Research Paper The Narrator in Ellison s Invisible Man Ralph Ellison’s Invisible Man is the story of an educated black man who has been oppressed and controlled by white men throughout his life. As the narrator, he is nameless throughout the novel as he journeys from the South, where he studies at an all-black college, to Harlem where he joins a Communist-like party known as the Brotherhood.
Fifth Business Essay Research Paper Fifth BusinessIn
Fifth Business Essay, Research Paper Fifth Business In the novel Fifth Business , the author Robertson Davies is successfully able to relate both the themes of magic and religion throughout. He achieves this relationship between the themes primarily through the characters and their actions. Dunstan Ramsay, Paul Dempster, Mary Dempster and Liselotte Vitzliputzli all help to illustrate the close relationship between magic and religion.
Dionysus The Peoples God Essay Research
Paper Dionysus: The Peoples God Dionysus was one the most influential of the Greek Gods. Even though he didn’t arrive in Greece until approximately 800 BC, the impact from his followers is still felt in the world we live in today. Dionysus was a demi-god meaning that he was only a half god, which makes his rise to Mount Olympus even more amazing.
Secret Identity Essay Research Paper Clark Kent
Secret Identity Essay, Research Paper Clark Kent is a mild-mannered reporter for the ?Daily Planet? newspaper. Born and raised in Smallville, Kansas; he now lives alone in an apartment in downtown Metropolis. He fits the mold of the stereotypical business man in any bustling city of commerce. With his suit, briefcase, and cellular phone, he can?t blend in more thoroughly, but who am I kidding? Underneath that tailored suit lies another person with a big ?S? on his chest.
Surprise Essay Research Paper Dan woke up
Surprise Essay, Research Paper Dan woke up suddenly and checked his alarm clock. He never liked that little thing, because he never quite figured out how to make it work. Jus1t as he suspected, the little display was showing 8:06 which meant that he had 24 minutes to get to work and eventually present the program to his irritating boss and the critics.
Three Universal Deadly Sins Essay Research Paper
Three Universal Deadly SinsThroughout history, mankind has looked back to the past, to seek the truth about morals, religion, and how they both impact and define civilization. Stories and myths from ancient Greece show overbearing resemblance to our own Bible as both shun the many temptations of our soul either by teaching the value of a characteristic or warning of the “ill fruits reaped”.
Reason To Live Essay Research Paper 1
Reason To Live Essay, Research Paper 1. One of Dunn s themes is the vulnerability of the human being alive in this world. In The Vanishing he writes that hurt hurts is one of life s truths. How, in the face of that hurt, does the human being find a reason for living?
Battle Royal Essay Research Paper BATTLE ROYAL
Battle Royal Essay, Research Paper BATTLE ROYAL Everyday , racism is perceived as one of the most negative aspects of society . When people think of racism , they obviously see hatred , evil , and ignorance . It has been a part of world culture
Battle Royal Essay Research Paper Battle RoyalThe
Battle Royal Essay, Research Paper Battle Royal The narrator of ?Battle Royal,? lived his life under the illusion that everybody had an equal chance in life. He desperately wanted and tried to please everyone, thinking that if he did he would eventually rise and become somebody great. He was a great speaker and his speeches won him great recognition, but he did not realize that nobody took him seriously.
Windows 95 Essay Research Paper Windows 95
Windows 95 Essay, Research Paper Windows 95 may very well be the most talked about software release in history. With more people than ever using personal computers, and given Microsoft’s dominance in this still growing market, Mr. Gates’ newest offering has caused quite a stir. As with any new product in this ultra-competitive industry, Windows 95 has come under intense scrutiny.
Catcher In The Rye And 1950S Television
Essay, Research Paper J.D. Salinger?s novel The Catcher in the Rye depicts life in the fifties as seen through the eyes of a disillusioned teenager. There is a vast difference between the life of a real 1950s family and that of a typical family portrayed through the television sitcoms of the day. The Catcher in the Rye is filled with examples that demonstrate how different real societies are.
Intrapersonal Communication Essay Research Paper 2
Intrapersonal Communication Essay, Research Paper INTRA PERSONAL COMMUNICATION FREUD (EGO) Self esteem Ego Ambition EMPATHY Reflection 3. Bierne TRANSACTIONAL ANALYSIS 4. INTERPERSONAL COMMUNICATION Berlo S
Ralph Ellison Essay Research Paper Ralph EllisonThe
Ralph Ellison Essay, Research Paper Ralph Ellison The Invisible Man Ralph Ellison manages to develop a strong philosophy through characterization in the Invisible Man. Ellison portrays the lonely narrator?s quest in struggling to search for his identity and an understanding of his times. The well development of the character lays out the foundation on the philosophy of finding and understanding himself.
Pearl1A Essay Research Paper MATERIAL SOCIETY MATERIAL
Pearl(1)(A) Essay, Research Paper MATERIAL SOCIETY, MATERIAL THOUGHTS Ever since Midas’ lust for gold, it appears to be that man hasacquired a greed and appetite for wealth. Juana, the Priest, andthe doctor have all undergone a change due to money. They areall affected by their hunger for wealth and inturn are the base fortheir own destruction, and the destruction of society.
Invisible Man Essay Research Paper Ralph Ellisons
Invisible Man Essay, Research Paper Ralph Ellison?s ?Invisible Man,? as told by the ?invisible man? himself, is the story of a man?s quest to separate his beliefs and values from those being pressed upon him. The narrator never gives his name in the story, which is shown later to have great significance. The narrator is a well-educated black man who has been kicked out of his college, and lied to by the school officials.
Commentary On Battle Royal Essay Research Paper
Ben Riley 7-24-00 Thoughts on Battle Royal Ralph Ellison?s short story, Battle Royal, takes place in any small town in the south. The main focus of this story is the reoccurring incidences of racial inequality. This is a story of several generations of an Afro-American family that dream about improving their lives in a racially segregated America.
Symbol Of The Briefcase In
“The Invisible Man” Essay, Research Paper While the civil war ended one form of slavery in America, another system of oppression was ready to take its place. In Ralph Ellison?s acclaimed novel Invisible Man, a young black, nameless narrator struggles through a series of hard-won lessons as he makes his journey from the Deep South to Harlem, New York, from naivet? to disenchantment, from illusion to insight.
King Midas Essay Research Paper Long ago
King Midas Essay, Research Paper Long ago, during the time of knights and dragons, there lived a king named Midas. He was considered one of the richest men on earth, but just like the many wealthy people around, money did not bring much happiness to him. Unsatisfied, he then assumed that perhaps being the richest among the rich could be the answer to his desires for a better life.
King Midas And His Golden Touch On
Contemporary Society Essay, Research Paper King Midas and His Golden Touch on Contemporary Society. Many believe that many pursuits of contemporary society, particularly our desire to accumulate wealth and the unintended consequences of these desires are modern day inventions. The Greek myth King Midas and the Golden Touch demonstrate that these desires along with their unintended consequences have existed for many centuries.
Dionysius Essay Research Paper DionysusDionysus was the
Dionysius Essay, Research Paper Dionysus Dionysus was the most widely worshipped and popular god in ancient Greece. It’s not difficult to see why; he was their god of wine, merriment, ritual dance, warm moisture, and later, civilization. He was often depicted as a handsome young man, dressed in fawnskin, and carrying a goblet and an ivy-covered staff.
The Pearl Essay Research Paper Ever since
The Pearl Essay, Research Paper Ever since Midas’ lust for gold, it appears to be that man has acquired a greed and appetite for wealth. Juana, the Priest, and the doctor have all undergone a change due to money. They are all affected by their hunger for wealth and inturn are the base for their own destruction, and the destruction of society.
The Pearl
– Greed Essay, Research Paper Ever since Midas’ lust for gold, it appears to be that manhas acquired a greed and appetite for wealth. Juana, the Priest,and the doctor have all undergone a change due to money. Theyare all affected by their hunger for wealth and inturn are thebase for their own destruction, and the destruction of society.Steinbeck’s “The Pearl” is a study of man’s self destruction through greed.
Male Teachers Essay Research Paper It is
Male Teachers Essay, Research Paper It is not very often that we see or hear of male teachers in preschools and elementary schools. Often times, male teachers in preschools and elementary schools are perceived as gay or looked down upon as being ?wimpy? because of the amount of sensitivity required to teach young children.
Hotel Security Essay Research Paper Hotel SecurityIn
Hotel Security Essay, Research Paper Hotel Security In the Hotel Whether traveling on business or pleasure it may become necessary to stay overnight in a hotel or motel. It is important to give some thought about security, and what hotel or motel you select, and what room you are willing to accept. The cost of the hotel room is not always the best predictor of how safe the room or property will be.
Inherit The Wind Essay Research Paper MahaThe
Inherit The Wind Essay, Research Paper Maha The Theme of Inherit the Wind The theme of Inherit the Wind by Jerome Lawrence and Robert Lee is the right to think. One example that supports the theme is that Drummond tries to prove Bert Cates is on trial because he uses his right to think. Drummond asks Howard?s opinion on morality, so he can establish that ?anyone in this courtroom . . . has the right to think? (64).